我想測試一下按鈕,但我不能讓一個動作監聽工作如何一個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