我正在尝试测试按钮,但我无法让 Action Listener 工作
public class ButtonTester implements ActionListener {
static JLabel Label = new JLabel("Hello Buttons! Will You Work?!");
public static void main(String[] args) {
//Creating a Label for step 3
// now for buttons
JButton Button1 = new JButton("Test if Button Worked");
// step 1: create the frame
JFrame frame = new JFrame ("FrameDemo");
//step 2: set frame behaviors (close buttons and stuff)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//step 3: create labels to put in the frame
frame.getContentPane().add(Label, BorderLayout.NORTH);
frame.getContentPane().add(Button1, BorderLayout.AFTER_LAST_LINE);
//step 4: Size the frame
frame.pack();
//step 5: show the frame
frame.setVisible(true);
Button1.setActionCommand("Test");
Button1.setEnabled(true);
Button1.addActionListener(this); //this line here won't work
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if("Test".equals(e.getActionCommand()))
{
Label.setText("It Worked!!!");
}
}
}
最佳答案
静态方法不与类的实例相关联,因此不能使用 this
。
您可以将所有代码从 main 移动到 ButtonTester 的非静态方法(例如,run()
)并从 main 执行类似这样的操作:
new ButtonTester().run();
您还可以为 ActionListener 使用匿名内部类:
Button1.addActionLister(new ActionListener() {
@Override public void actionPerformed (ActionEvent e) {
// ...
}
});
关于java - 如何在 Java 中将 ActionListener 添加到框架中的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18093548/