Java事件处理程序

时间:2009-02-19 14:09:26

标签: java swing event-handling

我正在编写一个小型Java应用程序(在Windows上,因此_on_vista附加到我的名字上)。

我有3个按钮,所有这些按钮都会对点击事件做出反应,但做不同的事情。

下面的代码是接受的方式还是有一种我不知道的清洁方式? 在一半,它的作用,在另一半,一些似乎不正确......

由于

cool_button_1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        coolfunction1();
    }
});

cool_button_2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        coolfunction2();
    }
});

// etc ...

被调用的函数将根据需要产生线程,依此类推。

更新 - 两者都很好(几乎相同)的答案。我接受了较低代表的人来分享财富。再次感谢你们。

5 个答案:

答案 0 :(得分:3)

是的,这是正确的方法。它有点笨拙(为了能够调用方法而必须编写五行代码)但那是Java :(

答案 1 :(得分:1)

那还不错。我更喜欢使用Actions并从中创建JButtons

Action fooAction = new AbstractAction() { ... };
JButton fooButton = new JButton(fooAction);

答案 2 :(得分:1)

这是正确的方法之一。

您正在使用匿名侦听器,但有一个替代

http://java.sun.com/docs/books/tutorial/uiswing/events/intro.html

上很好地解释了

您编写一个实现ActionListener并让它为您处理逻辑的类

答案 3 :(得分:0)

我会说代码很好,就像Java代码那样。这是Java经常被批评的冗长的一个很好的例子 - 在这种情况下由于缺少闭包。

答案 4 :(得分:0)

我倾向于这样做:

public class ButtonPanel implements ActionListener {
    JButton button1, button2, button3;
    public ButtonPanel() {
        button1 = new JButton(this);
        button2 = new JButton(this);
        button3 = new JButton(this):
        ...
    }

    public void ActionPerformed(ActionEvent e) {
        if( e.getSource() == button1 ) action1();
        else if( e.getSouce() == button2  ) action2();
        else if( e.getSource() == button3 ) action3();
    }
}