运行 JLabel点击方法
Running a method on click of JLabel
我想要的只是在单击 JLabel
后 运行 我的代码,但由于某种原因它无法正常工作,我无法弄清楚原因> [中没有错误=15=] 或控制台。
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")
});
实现它的一种方法如下:
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!");
}
});
我想要的只是在单击 JLabel
后 运行 我的代码,但由于某种原因它无法正常工作,我无法弄清楚原因> [中没有错误=15=] 或控制台。
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")
});
实现它的一种方法如下:
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!");
}
});