java如何将ActionEvent添加到JButton,以便在单击它时触发事件?
我希望能够将ActionListener添加到JButton,但似乎无法使其正常工作
我已经尝试添加ActionListener和ActionEvent,但两个方法都没有触发ActionPerformed方法
我不知道一个奇怪的方面是编译器让我去掉@Override关键字,因为接口是用来创建变量的,而不是实现的
这有区别吗?我相信你可以这样做,但我想我只是有点偏离了目标
代码:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class testInterfaces2 {
static ActionListener m;
static ActionEvent me;
testInterfaces2() {
}
public void actionPerformed(ActionEvent e) {
System.out.println("Mouse Clicked");
}
public static void main(String[] args) {
JFrame f = new JFrame("Test");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JButton pButton = new JButton("Print");
pButton.addActionListener(m);
//pButton.addActionListener(m.actionPerformed(me));
f.add("Center", pButton);
f.pack();
f.setVisible(true);
}
}
# 1 楼答案
这应该突出显示了您的第一个问题,
testInterfaces2
类不能重写actionPerformed
,因为它未在父类的任何部分或其父类中定义。这是因为testInterfaces2
没有直接或间接(通过继承)实现ActionListener
您的第二个问题是
m
是null
,您从未初始化过它更详细地看一下How to write ActionListeners
# 2 楼答案
我认为最好为每个按钮定义一个新的ActionListener。像这样
# 3 楼答案
它应该是这样的,并删除不需要的
ActionListener
和ActionEvent
变量@Override
除了对重写的方法进行编译时检查之外,不做任何额外的事情简单地说,您需要一个实现
ActionListener
的类,显然它实现了actionPerformed()
方法。只需创建该类的对象并传入addActionListener()
方法