2012-12-29 38 views
0

我試圖實現一個簡單的窗口,其中包含兩個按鈕YesNo如何從ActionEvent獲取所有JButton組件的源代碼?

Yes點擊我要禁用No按鈕和No按下時,我想禁用Yes按鈕。

我實現:

JButton btnYes = new JButton("Yes"); 
contentPane.add(btnYes); 
btnYes.setActionCommand("Yes"); 
btnYes.addActionListener(this); 

...同爲No按鈕...

現在我趕上在這個方法的事件:

public void actionPerformed(ActionEvent e) { 
    if(e.getActionCommand().equals("Yes")) 
    { 
     //I know how to get the button that caused the event 
     //but I don't know how to disable the OTHER button. 
     JButton source = (JButton)e.getSource(); 
     //Handle the source button... 
    } 

} 

在上述方法中,我可以訪問導致事件的按鈕,但不能訪問其他按鈕。

獲取按鈕的最佳方法是什麼?

+1

使用'JCheckBox'或'JToggleButon'。 –

回答

1

您應該只是將ActionListener實現爲Dialog類的嵌套類,在這種情況下,您將可以完全訪問外部類的所有字段(在創建它們時應該在其中存儲對按鈕的引用)。

不好的髒解決方案(不應該使用)仍然存在:通過JButton的getParent(),然後通過父母孩子的getChildren()導航到連擊。只是爲了表明這是可能的。

+0

但後來我必須將按鈕更改爲「最終」,不是嗎? – Maroun

+0

@MarounMaroun如果將按鈕存儲爲對話框類字段,則不需要。 – Daniil

1

你可以使用一個JButton數組作爲類的成員變量,並檢查其實例didnt導致事件:

for (JButton button: buttonArray) { 
    if (button != source) { 
     button.setEnabled(false); // disable the other button 
    } 
} 
+0

它被認爲是一個好設計嗎? – Maroun

+0

恕我直言,這是一個很好的設計。該數組不一定是您的主類的類成員變量。例如,它可以是[Action](http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html)類的成員變量。這將是一個專門用於管理按鈕之間交互的類。 – Reimeus

相關問題