我想测试一下按钮,但我不能让一个动作监听工作如何一个ActionListener添加到按钮的边框在Java中
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!!!");
}
}
}
您应该在Swing事件线程上使用SwingUtilities.invokeLater()在main()中创建Swing组件。让ButtonTester实现Runnable,将代码从main()移动到run(),然后从main()中执行SwingUtilities.invokeLater(new ButtonTester())将一次解决许多问题。 –
请学习java命名约定并遵守它们。 – kleopatra