2011-06-14 56 views
1
JFrame myframe = new JFrame("My Sample Frame"); 
    JButton mybutton = new JButton("Okay"); 

有人可以向我解釋這些部分。JFrame ActionListener

mybutton.addActionListener(new ActionListener(){ 

    public void actionPerformed(ActionEvent evt){ 

    //Assuming that the content here will do something. 

    } 
+2

訪問(http://stackoverflow.com/questions/5335161/how-does-this-method-work) – 2011-06-14 14:33:33

回答

4

您應該閱讀本教程約writing Event Listeners

+0

+1,雖然你並沒有真正 「解釋」任何事情......你只是把OP引到其他地方。 – mre 2011-06-14 13:39:19

4

你究竟對代碼不瞭解?

該代碼將一個動作偵聽器添加到該按鈕。動作偵聽器的actionPerformed方法將在單擊按鈕時調用。

請注意,這裏使用的是anonymous inner class

+0

嗨,謝謝你Jesper。 我不習慣匿名內部類,事實上我只是現在就知道它。 。謝謝你,還有更多的權力。最後一個問題是這些練習的好壞,我的意思是我設置事件監聽器的方式。 – kebyang 2011-06-14 13:46:26

+1

這並不是不好的做法,事實上,設置事件處理程序通常是使用匿名內部類來完成的,就像您所展示的示例一樣。 – Jesper 2011-06-14 14:36:39

2

爲了讓按鈕對事件(例如點擊)作出反應,它必須有一個ActionListener

在您發佈的代碼,你正在創建一個匿名類實現ActionListener

public void mySetupFunction(){ 

    mybutton.addActionListener(new ActionListener(){ 

    public void actionPerformed(ActionEvent evt){ 
     //Do something when the button is clicked 
    }); 
} 

是一樣的做:

public void mySetupFunction(){ 

    mybutton.addActionListener(new MyEventHandler()); 
} 

有:

public class MyEventHandler implements ActionListener{ 
    public void actionPerformed(ActionEvent evt){ 
     //Do something when the button is clicked 
    } 
} 
4

匿名內部類在這裏使用。

您在技術上實現了ActionListener。當你打電話addActionListener方法:

mybutton.addActionListener(new ActionListener(){ 

public void actionPerformed(ActionEvent evt){ 

    //Assuming that the content here will do something. 

} 

您創建了一個匿名類,或實現ActionListener的沒有名字的類的實例。

出於同樣請訪問 this link .