草庐IT

java - 还记得鼠标点击的位置吗?数组列表?哈希码?

coder 2023-09-02 原文

抱歉,我删除了我的 APPLES 和 CATS 示例 :) 这是我的问题的更新版本!

我在这里失去了理智。我需要一个能启发我的人。我试过几次在这里解释我的问题。希望这一次,我的问题会更容易理解。

基本上我有这个框架,并且显示了一个图像。右侧有一个 JList,底部还有另一个 JLabels 面板。这是我的框架的屏幕截图。

当我单击图像时,会弹出一个 JOptionPane,就像这样。然后我输入我的输入。我的 JList 是一个 ArrayList,所以我输入的所有内容都会添加到底部的 JList 和 JPanel。

现在,当我将鼠标悬停在我单击的部分时,您会注意到正方形消失了)。它仅在我单击图像以及将标签悬停在底部时出现。我的标签,截至目前是 LOLZ NOSE 和 INPUT HERE。

我想做的是,当我将鼠标悬停在标签上时,例如 INPUT HERE,它会再次显示正方形,其中包含我点击的部分。我现在的问题是当我点击 NOSE 时,它应该在 Nose 部分显示一个正方形和一个带有黑色 bg 的名称 NOSE,它没有显示。此外,仅显示最后一个标签的方 block ,忽略其他标签的点击位置。

如何获得一个标签来记住我点击的位置?人们说我应该使用 ArrayLists 或 HashCodes 但是我不知道如何实现它们。感谢任何可以提供帮助的人。

编辑:我已经完成了矩形,顺便说一下。它仅针对输入的最后一个标签显示。以下是请求的一些代码片段!

我如何在 JLabel 上设置文本并更新 JList:

public void updateLabel(){

        StringBuilder text = new StringBuilder(); //creates empty builder, capacity 16

        for(Object s: tagModel.toArray()) //returns an array containing the elements of the tagModel
            text.append(" " + s);

        repaint();      
        hoverLabel.setText(text.toString()); //returns a String
        hoverLabel.addMouseMotionListener(this);
        hoverPanel.add(hoverLabel);

    }

点击时我的 mouseListener:

@Override
    public void mouseClicked(MouseEvent event) {
        // TODO Auto-generated method stub

        x = event.getX();
        y = event.getY();

        isRectPresent = true;
        repaint();

        input = JOptionPane.showInputDialog("Enter tag name:");

        if((input != null) && !input.isEmpty()){
            tagModel.addElement(input);
        }
    }

悬停时我的 mouseMotionListener:

@Override
    public void mouseMoved(MouseEvent e) {
        // TODO Auto-generated method stub

        xpos = e.getX(); //gets where the mouse moved
        ypos = e.getY(); 

        //checks if the mouse is inside the bounds of the rectangle
        if (xpos > x && xpos < x + 100 && ypos > y && ypos < y + 100)
            isRectPresent = false;

        if(e.getSource() == hoverLabel){
            isRectPresent = true;
            repaint();
        }

        repaint();
    }

我是如何画画的:

    public void paintComponent(Graphics g){ 
            Graphics2D g2 = (Graphics2D) g;

            g2.drawImage(image, 0, 0, null);

            if(image != null && isRectPresent){                 
                            Stroke stroke = g2.getStroke();
                g2.setStroke(new BasicStroke(4));
                g2.setColor(Color.WHITE);
                g2.drawRect(x-50, y-50, 100, 100);
                g2.setStroke(stroke);
            }else{
                if(xpos > x && xpos < x + 100 && ypos > y && ypos < y + 100){
                    g.setColor(Color.BLACK);
                    g.fillRect(x-50, y-50, 100, 25);
                    g.setColor(Color.WHITE);
                    g.setFont(new Font("Tahoma", Font.BOLD, 12));
                    g.drawString(input, x-30, y-30);
                }
            }
        }

如果您想让我添加更多片段,请告诉我! :)

最佳答案

你应该创建一个 HashMap,像这样说:

Map linkSet = new HashMap();

每当您单击绘图并创建标签时,使用 put 方法将 JLabel 和图像上的点添加到集合中,并将 JLabel 作为键,将 Point 作为值。然后在 JLabel 的 MouseMotionListener 中,使用您的标签作为键,并使用 map 的 get(...) 方法从集合中获取对应的点。

编辑:
根据 alicedimarco 的评论更正。再次感谢!

编辑 2
我想你想再次使用 map 。如果你有一个 map ,你可以让它从 JLabel 或 JList 的字符串中检索兴趣点,然后将这个点传递给绘制图像的类,让它使用点来绘制一个矩形。例如,您可以为图像绘制类提供一个名为 displayPoint 的点字段和一个名为 setDisplayPoint(Point p) 的方法。它可以像这样简单:

public void setDisplayPoint(Point p) {
  this.displayPoint  = p;
  repaint();
}

并假设感兴趣的对象以该点为中心,在 paintComponent 方法中使用 displayPoint:

protected void paintComponent(Graphics g) {
  super.paintComponent(g);
  // draw image
  if (img != null) {
     g.drawImage(img, X_SHIFT, Y_SHIFT, null);
  }

  // if displayPoint not null, draw the surrounding rectangle
  if (displayPoint != null) {
     g.setColor(RECT_COLOR);
     int x = displayPoint.x - RECT_WIDTH / 2;
     int y = displayPoint.y - RECT_WIDTH / 2;
     int width = RECT_WIDTH;
     int height = RECT_WIDTH;
     g.drawRect(x, y, width, height);
  }
}

编辑 3:
要获得鼠标点击,这非常简单,只需将 MouseListener 添加到保存图像的组件即可:

     // !! added
     imgRect.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
           imgMousePressed(e);
        }
     }); 

在从这个鼠标监听器调用的代码中,使用 JOptionPane 获取用户选择的标签名称,并将结果字符串添加到 listDataModel 中,以便在 JList 和 stringPointMap 中一起看到使用从 MouseEvent 获得的点,以便您可以将字符串映射到点并能够检索它:

// !! added
private void imgMousePressed(MouseEvent e) {
  String result = JOptionPane.showInputDialog(this,
        "Please enter name for this point on image:");
  if (result != null) {
     stringPointMap.put(result, e.getPoint());
     listDataModel.addElement(result);
  }
}

就是这样。

然后把它们放在一起:

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class ImageRectMain extends JPanel {
   private ImageRect imgRect;
   private DefaultListModel listDataModel = new DefaultListModel();
   private JList list = new JList(listDataModel);
   private Map<String, Point> stringPointMap = new HashMap<String, Point>();

   public ImageRectMain() {
      String nose = "Nose";
      String ear = "Ear";
      String rightEye = "Right Eye";
      String leftEye = "Left Eye";
      listDataModel.addElement(ear);
      listDataModel.addElement(nose);
      listDataModel.addElement(rightEye);
      listDataModel.addElement(leftEye);
      stringPointMap.put(nose, new Point(480, 500));
      stringPointMap.put(ear, new Point(270, 230));
      stringPointMap.put(rightEye, new Point(380, 390));
      stringPointMap.put(leftEye, new Point(662, 440));

      MouseAdapter listMouseAdapter = new MouseAdapter() {
         @Override
         public void mouseMoved(MouseEvent e) {
            listMouseMoved(e);
         }

         @Override
         public void mouseExited(MouseEvent e) {
            listMouseExited(e);
         }

      };
      list.addMouseMotionListener(listMouseAdapter);
      list.addMouseListener(listMouseAdapter);

      try {
         imgRect = new ImageRect();

         // !! added
         imgRect.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
               imgMousePressed(e);
            }
         }); 

         JPanel eastPanel = new JPanel();
         eastPanel.setLayout(new BoxLayout(eastPanel, BoxLayout.PAGE_AXIS));
         eastPanel.add(new JLabel("You have tagged the following:"));
         eastPanel.add(new JScrollPane(list));
         eastPanel.add(Box.createVerticalGlue());
         eastPanel.add(Box.createVerticalGlue());
         eastPanel.add(Box.createVerticalGlue());
         eastPanel.add(Box.createVerticalGlue());
         setLayout(new BorderLayout());
         add(imgRect, BorderLayout.CENTER);
         add(eastPanel, BorderLayout.EAST);
      } catch (MalformedURLException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   // !! added
   private void imgMousePressed(MouseEvent e) {
      String result = JOptionPane.showInputDialog(this,
            "Please enter name for this point on image:");
      if (result != null) {
         stringPointMap.put(result, e.getPoint());
         listDataModel.addElement(result);
      }
   }

   private void listMouseExited(MouseEvent e) {
      imgRect.setDisplayPoint(null);
   }

   private void listMouseMoved(MouseEvent e) {
      int index = list.locationToIndex(e.getPoint());
      Object value = listDataModel.get(index);
      if (value != null) {
         Point point = stringPointMap.get(value.toString());
         if (point != null) {
            imgRect.setDisplayPoint(point);
         }
      }
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("ImageRectMain");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new ImageRectMain());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

@SuppressWarnings("serial")
class ImageRect extends JPanel {
   public static final String IMAGE_PATH = "http://i.stack.imgur.com/7oNzg.jpg";
   private static final int DEFAULT_W = 687;
   private static final int DEFAULT_H = 636;
   private static final int X_SHIFT = -6;
   private static final int Y_SHIFT = -26;
   private static final Color RECT_COLOR = Color.pink;
   private static final int RECT_WIDTH = 40;
   private BufferedImage img;
   private Point displayPoint = null;

   public ImageRect() throws MalformedURLException, IOException {
      img = ImageIO.read(new URL(IMAGE_PATH));
   }

   public void setDisplayPoint(Point p) {
      this.displayPoint = p;
      repaint();
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      if (img != null) {
         g.drawImage(img, X_SHIFT, Y_SHIFT, null);
      }
      if (displayPoint != null) {
         g.setColor(RECT_COLOR);
         int x = displayPoint.x - RECT_WIDTH / 2;
         int y = displayPoint.y - RECT_WIDTH / 2;
         int width = RECT_WIDTH;
         int height = RECT_WIDTH;
         g.drawRect(x, y, width, height);
      }
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(DEFAULT_W, DEFAULT_H);
   }
}

关于java - 还记得鼠标点击的位置吗?数组列表?哈希码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8330787/

有关java - 还记得鼠标点击的位置吗?数组列表?哈希码?的更多相关文章

  1. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  2. ruby - 多次弹出/移动 ruby​​ 数组 - 2

    我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby​​数组,我们在StackOverflow上找到一

  3. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  4. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  5. ruby - 检查数组是否在增加 - 2

    这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife

  6. ruby - RVM 使用列表[0] - 2

    是否有类似“RVMuse1”或“RVMuselist[0]”之类的内容而不是键入整个版本号。在任何时候,我们都会看到一个可能包含5个或更多ruby的列表,我们可以轻松地键入一个数字而不是X.X.X。这也有助于rvmgemset。 最佳答案 这在RVM2.0中是可能的=>https://docs.google.com/document/d/1xW9GeEpLOWPcddDg_hOPvK4oeLxJmU3Q5FiCNT7nTAc/edit?usp=sharing-知道链接的任何人都可以发表评论

  7. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  8. ruby - 如果指定键的值在数组中相同,如何合并哈希 - 2

    我有一个这样的哈希数组:[{:foo=>2,:date=>Sat,01Sep2014},{:foo2=>2,:date=>Sat,02Sep2014},{:foo3=>3,:date=>Sat,01Sep2014},{:foo4=>4,:date=>Sat,03Sep2014},{:foo5=>5,:date=>Sat,02Sep2014}]如果:date相同,我想合并哈希值。我对上面数组的期望是:[{:foo=>2,:foo3=>3,:date=>Sat,01Sep2014},{:foo2=>2,:foo5=>5:date=>Sat,02Sep2014},{:foo4=>4,:dat

  9. ruby - 在 Ruby 中用键盘诅咒数组浏览 - 2

    我正在尝试在Ruby中制作一个cli应用程序,它接受一个给定的数组,然后将其显示为一个列表,我可以使用箭头键浏览它。我觉得我已经在Ruby中看到一个库已经这样做了,但我记不起它的名字了。我正在尝试对soundcloud2000中的代码进行逆向工程做类似的事情,但他的代码与SoundcloudAPI的使用紧密耦合。我知道cursesgem,我正在考虑更抽象的东西。广告有没有人见过可以做到这一点的库或一些概念证明的Ruby代码可以做到这一点? 最佳答案 我不知道这是否是您正在寻找的,但也许您可以使用我的想法。由于我没有关于您要完成的工作

  10. ruby - 如何在 Grape 中定义哈希数组? - 2

    我使用Ember作为我的前端和GrapeAPI来为我的API提供服务。前端发送类似:{"service"=>{"name"=>"Name","duration"=>"30","user"=>nil,"organization"=>"org","category"=>nil,"description"=>"description","disabled"=>true,"color"=>nil,"availabilities"=>[{"day"=>"Saturday","enabled"=>false,"timeSlots"=>[{"startAt"=>"09:00AM","endAt"=>

随机推荐