简体   繁体   中英

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

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!");
            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM