开发者

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

I want to have a clickable icon (an Im开发者_JAVA技巧ageIcon 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.


You could have two separate JLabel inside a container, the first with text, the second with just the icon, and add a mouse listener to the icon JLabel.


This method is very hacky but worked for me.

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

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜