单击JLabel运行方法

时间:2015-09-15 07:51:13

标签: java swing jlabel mouselistener

我想要的是在点击JLabel之后运行我的代码但由于某种原因它只是不工作而我无法解决为什么> IDE或控制台中没有错误。

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

1 个答案:

答案 0 :(得分:2)

你可以实现它的一种方式是:

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

但是,正如所建议的那样,最好在JButton处使用ActionListener

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