如何用匿名类在JPanel上加 按钮监听事件

来源:百度知道 编辑:UC知道 时间:2024/06/22 16:49:21
我为什么单击在JFrame上的按钮好用,换成JPanel上就不好用了

private void addButtonListener() {
changeMonthPanel.getLastYearBtn().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("dddddfdfdsfsf");
}
});
}
就是这样的用匿名类做的
public JButton getLastYearBtn() {
return lastYearBtn;
}

这是getLastYEarBtn() 的方法 。有什么不对吗

你这段程序没有问题,不知你的getLastYearBtn()返回的按钮有没有正确设置。

这样写是没有问题的:
JPanel panel;
JButton button;
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
panel.add(button);

或者你可以考虑这样写:
JButton button = new JButton(new AbstractAction("Button Name") {
public void actionPerformed(ActionEvent e) {
System.out.println("Button Clicked");
}
});