【问题标题】:How to add Mouse listener to an ImageIcon embedded in a JLabel?如何将鼠标侦听器添加到嵌入在 JLabel 中的 ImageIcon?
【发布时间】:2011-06-11 11:13:19
【问题描述】:

我想在 JLabel 中有一个可点击的图标(一个 ImageIcon 对象)。如何将 MouseListener 或任何 ActionListener 添加到该图标。有没有其他方法可以知道图标是否被点击?我使用 JLabel 的 setIcon() 方法来设置其图标。

谢谢。

【问题讨论】:

标签: java swing jlabel


【解决方案1】:

您可以在一个容器内有两个单独的 JLabel,第一个带有文本,第二个只带有图标,并为图标 JLabel 添加鼠标侦听器。

【讨论】:

  • 我希望有一种聪明的方法可以使用鼠标事件的 X 和 Y 位置并查看它是否在图标的边界内,但遗憾的是描述图标在其中的位置的矩形JLabel 在 LabelUI 中是私有的,因此即使继承 LabelUI 也不会让您访问它。但是,它确实调用了 SwingUtilities.layoutCompoundLabel(),其中一个参数是图标的 Rectangle,因此如果您真的需要,您可以将 SwingUtilities 子类化以截获该信息并将其存储在某处。但真的,我不会打扰。只需使用两个组件。
【解决方案2】:

这种方法很老套,但对我有用。

    JLabel.addMouseListener(new MouseAdapter(){
        public void mousePressed(MouseEvent me){
            try {
                Robot robot = new Robot();
                if(JLabel.getBounds().contains(me.getPoint()) && !robot.getPixelColor(me.getXOnScreen(),me.getYOnScreen()).equals(page.getBackground())){
                    //Do action here
                }
            } catch (AWTException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
        }
    });

【讨论】:

    【解决方案3】:

    您可以使用此代码来解决您的问题:

    public  class Test extends JFrame {
        private JLabel label;
        ImageIcon icon = new ImageIcon("example.gif");
        public Test(){
            label = new JLabel(icon);
            label.addMouseListener(new MouseListener() {
    
            public void mouseClicked(MouseEvent e) {
            //for example    
                JOptionPane.showMessageDialog(null, "Hello");
    
            }
    
            public void mousePressed(MouseEvent e) {
            }
    
            public void mouseReleased(MouseEvent e) {
            }
    
            public void mouseEntered(MouseEvent e) {
            }
    
            public void mouseExited(MouseEvent e) {
            }
        });
    }
    

    }

    【讨论】:

    • 这对原始发帖人的问题没有帮助。他知道如何创建和使用 MouseListener,但他只想听 JLabel 的图像部分。
    猜你喜欢
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多