2013-11-24 29 views
1

我想跟蹤按特定順序點擊的特定組件。使用getSource處理未知類型組件的操作

我使用和的getSource標誌是這樣的:

public void actionPerformed(ActionEvent e) { 

JButton q = (JButton)e.getSource(); 
JRadioButton w = (JRadioButton)e.getSource(); 

    if (q.equals(mybutton)) { 
     if (flag == false) { 
      System.out.print("test"); 
      flag = true; 
     } 
    } 

這完全適用Jbutton將,這個問題可以用它JradioButton將也。如果我對它們都使用getSource,則單擊一個按鈕將導致拋出異常錯誤,因爲該按鈕不能轉換爲Radiobutton。

我該如何解決這個問題?

回答

2

您可以使用==來比較參考值,因爲參考值不會改變。

if(e.getSource() == radBtn1){ 
// do something 
} 

我已經在過去使用過它,它對我來說就像一個魅力。

至於班級演員問題,您需要使用instanceof來檢查事件來源屬於哪個班級。如果原因是JButton,並且您盲目地將其轉換爲JRadioButton,則會導致例外。您需要:

Object source = e.getSource(); 
if (source instanceof JButton){ 
    JButton btn = (JButton) source; 
} else if (source instanceof JRadioButton){ 
    JRadioButton btn = (JRadioButton) source; 
} 
+1

感謝您的回答。我嘗試過使用instanceof,但是我從if語句中得到錯誤「變量[Jbutton/Jradiobutton]可能未被初始化」。 – user2079483

+0

@ user2079483在聲明你的'JRadioButton'的地方,只需將它初始化爲'null'即可。然後,在某個地方使用構造函數來給它一個值。 –

相關問題