如何将ActionListener添加到Java中的框架中的按钮

时间:2013-08-07 02:16:18

标签: java swing jframe jbutton actionlistener

我正在尝试测试按钮,但我无法让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!!!");
    }
  }

}

3 个答案:

答案 0 :(得分:3)

thisstatic方法中没有上下文

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

<强>更新

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

答案 1 :(得分:3)

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

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

new ButtonTester().run();

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

Button1.addActionLister(new ActionListener() {
    @Override public void actionPerformed (ActionEvent e) {
        // ... 
    }
});

答案 2 :(得分: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!!!");
    }
  }
}