2010-09-01 56 views
6

當定義一個簡單的點擊JButton的行爲時,這是正確的方法嗎?而且,有什麼區別?addMouseListener或addActionListener或JButton?

JButton but = new JButton(); 
but.addActionListener(new ActionListener() {   
    public void actionPerformed(ActionEvent e) { 
     System.out.println("You clicked the button, using an ActionListener"); 
    } 
}); 

JButton but = new JButton(); 
but.addMouseListener(new java.awt.event.MouseAdapter() { 
    public void mouseClicked(java.awt.event.MouseEvent evt) { 
     System.out.println("You clicked the button, using a MouseListenr"); 
    } 
}); 

回答

6

MouseListener是一個Swing中的低級事件監聽器(順便說一句,AWT)。

ActionListener是更高級別,應該使用。

雖然比ActionListener好,但應該使用javax.swing.Action(實際上它是ActionListener)。

使用Action允許在多個小部件(如JButton,JMenuItem ...)中共享它;您不僅可以共享按下按鈕/菜單時觸發的代碼,還可以共享狀態,尤其是操作(及其關聯的小部件)是否啓用的事實。

1

您應該能夠按使用鍵盤也該按鈕。所以,如果你只添加鼠標監聽器,如果使用鍵盤,你將不會得到'新聞'事件。

我會爲行動監聽者去,這更清楚。

0

當Button觸發Action事件時會調用註冊的ActionListener,當小部件檢測到鼠標單擊時調用MouseListener

在您的示例中,當您使用鼠標點擊按鈕時,兩種方法都顯示相同的行爲。但要注意按鈕並按SPACE,這應該觸發一個操作事件並觸發Action Listener而不是鼠標偵聽器。

建議您在按鈕上使用ActionListener,否則您將無法用鍵盤控制應用程序,或者您需要添加另一個關鍵事件偵聽器。

-2

如果您想單擊Jbutton時執行某些操作,則動作偵聽器會更好,因爲如果用戶在JButton上按下鼠標,然後稍稍移動鼠標,鼠標偵聽程序不會識別鼠標在按鈕上的單擊然後釋放鼠標按鈕,同時保持在整個時間內的按鈕,但動作偵聽器。 MouseListener要求鼠標點擊在鼠標按下和鼠標釋放之間沒有移動,這對我的用戶來說並非如此。

相關問題