How to add Mouse listener to an ImageIcon embedded in a JLabel?

I want to have a clickable icon (an ImageIcon object) inside a JLabel. How can I add a MouseListener or any ActionListener just to that Icon. Is there any other way to know if the icon has been clicked? I use the setIcon() method for the JLabel to set its icon.

Thanks.


您可以在容器中放置两个单独的JLabel,第一个使用文本,第二个使用图标,并将鼠标侦听器添加到图标JLabel。


这种方法非常黑,但为我工作。

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

you can use this code to solving your problem:

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

}

链接地址: http://www.djcxy.com/p/67656.html

上一篇: 自定义JLabel图标

下一篇: 如何将鼠标监听器添加到嵌入在JLabel中的ImageIcon中?