Search code examples
javaswingjlabelmouselistener

Running a method on click of JLabel


All I want is to run my code after I have clicked the JLabel but for some reason it's just not working and I can't work out why> There are no errors in IDE or console.

final JLabel lblStatus = new JLabel(new ImageIcon(
                Main.class.getResource("/com/daniel/status1.png")));
        frame.getContentPane().add(lblStatus, BorderLayout.EAST);

        lblStatus.addMouseListener(new MouseAdapter() {

            public void mouseClicked(MouseEvent  arg0) {
            System.out.println("Clicked") 
            });

Solution

  • One way you could achieve it would be something like:

    JLabel label = new JLabel("Click me");
            label.addMouseListener(new MouseListener() {
                public void mouseClicked(MouseEvent e) { System.out.println("Clicked me!"); }
                public void mouseEntered(MouseEvent e) {}
                public void mouseExited(MouseEvent e) {}
                public void mousePressed(MouseEvent e) {}
                public void mouseReleased(MouseEvent e) {}
            });
    

    But, as suggested, it would be better to use a JButton here, with an ActionListener:

    JButton button = new JButton("Push me");
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Pushed me!");
                }
            });