1

我正在尝试测试按钮,但无法让动作侦听器工作

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!!!");
    }
  }

}
4

3 回答 3

3

thisstatic在方法中没有上下文

相反,请尝试使用类似Button1.addActionListener(new ButtonTester());...

更新

您可能还想查看Initial Threads,因为 Swing 有一些特殊要求......

于 2013-08-07T02:18:08.857 回答
3

静态方法与类的实例无关,因此this不能使用。

您可以将所有代码从 main 移动到 ButtonTester 的非静态方法(例如,run()例如),然后从 main 执行类似的操作:

new ButtonTester().run();

您还可以为 ActionListener 使用匿名内部类:

Button1.addActionLister(new ActionListener() {
    @Override public void actionPerformed (ActionEvent e) {
        // ... 
    }
});
于 2013-08-07T02:18:38.010 回答
1

java说你不能从静态上下文中访问一个非静态实体(这是指一个非静态对象并且main()是静态的),所以我们使用构造函数进行初始化:

public class ButtonTester implements ActionListener {
static JLabel Label = new JLabel("Hello Buttons! Will You Work?!");
ButtonTester()  //constructor
{
 //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
}


public static void main(String[] args) {
ButtonTester test1=new ButtonTester();// constructor will be invoked and new object created


}
@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    if("Test".equals(e.getActionCommand()))
    {
        Label.setText("It Worked!!!");
    }
  }
}
于 2013-08-07T04:20:13.310 回答