记住其中鼠标单击?的ArrayList?散列codeS? [英] Remembering where a mouse clicked? ArrayLists? HashCodes?

查看:180
本文介绍了记住其中鼠标单击?的ArrayList?散列codeS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起球员,我删除了我的苹果和CATS例如:)这里是我的问题的更新版本!

Sorry guys, I deleted my APPLES and CATS example :) Here's the updated version of my question!

我在这里失去了我的理智。我需要有人谁可以赐教。我试过几次,在这里解释我的问题。我们希望,这一次,我的问题会比较容易理解了。

I'm losing my sanity here. I need someone who can enlighten me. I've tried a couple of times explaining my problem here. Hopefully, this time, my question will be easier to understand.

基本上我有这个框架,并有显示的图像。有在右边一个JList和还有另一个面板在底部的JLabel。这里是我的帧的撷取画面。

Basically I have this frame, and there's an image displayed. There is a JList on the right, and there is another panel for JLabels at the bottom. Here's a screencap of my frame.

当我点击的形象,一个的JOptionPane弹出,就像这样。我进入我的输入。我JList的是一个ArrayList,所以一切我需要输入被添加到JList和在JPanel底部。

When I click on the image, a JOptionPane pops out, like so. And I enter my input. My JList is an ArrayList, so everything I input is added to the JList and the JPanel at the bottom.

现在,当我将鼠标悬停在那里,我点击了一部分,你注意到广场消失)。它只有当我点击的形象出现,当我徘徊在底部的标签。我的标签,截至目前有LOLZ鼻子和在此输入。

Now, when I hover on the the part where I clicked, you noticed that the square disappeared). It only appears when I click the image, and when I hover the label at the bottom. My labels, as of now are LOLZ NOSE and INPUT HERE.

我想要做的是,当我将鼠标悬停在标签上,例如这里输入,它再次显示了广场,在那里为特色点击我的一部分。我现在的问题是,当我的鼻子,这是为了展示在鼻子上一部分,并与黑色BG一个名字鼻子单击正方形,它没有显示。此外,只有最后一个标签的正方形所示,不顾其他标签的位置点击。

What I want to do is when I hover on the label, for example INPUT HERE, it shows the square again, featuring the part where I clicked. My problem now is when I click on NOSE, which is supposed to be showing a square on the nose part and a the name NOSE with black bg, IT IS NOT SHOWING. Also, only the last label's square is shown, disregarding the other labels' position clicked.

我如何得到一个标签要记得点击我做的立场?人们说我应该使用的ArrayList或哈希codeS,但是我不知道如何实现它们。谢谢你的人谁可以提供帮助。

How do I get a label to remember the position of the click I make? People said I should use ArrayLists or HashCodes however I have no idea how to implement them. Thank you to anyone who can help.

编辑:我已经做了矩形,顺便说一句。它仅是示出了用于输入的最后一个标签。下面是一些code段的要求!

I've already done the rectangle, btw. It's showing only for the last label inputted. Here are some of the code snippets requested!

我是如何设置的JLabel中的文本更新JList的:

How I'm setting the text on JLabel and updating the 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:

My mouseListener upon click:

@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:

My mouseMotionListener upon hovering:

@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);
                }
            }
        }

如果你要我多补充一些片段,只是告诉我! :)

If you want me to add some more snippets, just tell me! :)

推荐答案

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

You should create a HashMap, say something like:

地图LINKSET =新的HashMap();

Map linkSet = new HashMap();

每当你点击在图纸上,并创建一个标签,在图像上添加的JLabel和点用用的JLabel为重点和点作为价值put方法的集合。然后在JLabel的的MouseMotionListener,使用标签作为重点,并取得使用地图的的get(...)方法设定相应的点。

And whenever you click on the drawing and create a label, add the JLabel and the point on the image to the set using the put method with the JLabel as the key and the Point as the value. Then in the JLabel's MouseMotionListener, use your label as a key and obtain the corresponding point from the set using the map's get(...) method.

修改结果
更正按aliced​​imarco的评论。再次,感谢!

edit:
Corrected as per alicedimarco's comment. Again, thanks!

修改2 结果
我认为要再次使用地图。如果你有一个地图,你可以把它检索从JLabel的或JList的弦乐兴趣点,然后通过这个指向的绘画图像类,让它用点来绘制一个矩形。例如,你可以给图像拉丝类称为displayPoint一个点字段,以及一个名为setDisplayPoint(点P)方法。它可以像这样简单:

edit 2
I think you want again to use a Map. If you have a Map, you can have it retrieve the Point of interest from the JLabel's or the JList's String, and then pass this Point to the class that's drawing the image and let it use the Point to draw a rectangle. For instance you could give the image drawing class a Point field called displayPoint, and a method called setDisplayPoint(Point p). It can be as simple as this:

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

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

and assuming that the object of interest is centered at that point, use the displayPoint in the paintComponent method:

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添加到包含图像组件:

edit 3:
To get mouse clicks, it's quite easy, simply add a MouseListener to the component that holds the image:

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

而在你的code是从这款鼠标监听器调用时,使用的JOptionPane获取用户的选择标记名称,并添加结果String来既ListDataModel业务,使其出现在JList和也用点stringPointMap一起从获得的MouseEvent,以便您可以映射字符串点,并能找回它:

And in your code that is called from this mouse listener, use a JOptionPane to get the user's choice of tag name, and add the resulting String to both the listDataModel so that it is seen in the JList and also in the stringPointMap together with the Point obtained from the MouseEvent so that you can map the String to the Point and be able to retrieve it:

// !! 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);
   }
}

这篇关于记住其中鼠标单击?的ArrayList?散列codeS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆