How do I create an event handler for a JLabel?

Spencer B picture Spencer B · Jul 19, 2011 · Viewed 10.2k times · Source

I want to make it so that if I click on the JLabel, the label becomes a new label with another image attached to it.

So far my code looks like:

public class Picture extends JFrame  {

    private ImageIcon _image1;
    private ImageIcon _image2;
    private JLabel _mainLabel;
    private JLabel _mainLabel2;

    public Picture(){
        _image1 = new ImageIcon("src/classes/picture1.jpg");
        _image2 = new ImageIcon("src/classes/picture2.jpg");
        _mainLabel = new JLabel(_image1);
        _mainLabel2 = new JLabel(_image2);

        add(_mainLabel);

        pack();
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Answer

Harry Joy picture Harry Joy · Jul 19, 2011

Add mouseListener to your JLable and in mouseClicked(mouseEvent) method change icon of JLabel.

A sample code may be:

  jLabel.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            jLabel.setIcon(newIcon);
        }
    });