2013-05-03 62 views
1

我有一個包含許多對象的JPanel,並且可以執行一個主要操作:計算。有一個按鈕可以做到這一點,而且還有一個JTextField和其他用戶可能想要按下輸入的組件。例如,如果您從JComboBox中選擇了一些內容並按下回車鍵,計算就會發生。是否有一種簡單的方法將一個監聽器添加到JPanel的所有內容中,而不是將ActionListeners添加到每個組件中?將偵聽器添加到JPanel中的所有對象

+0

http://stackoverflow.com/questions/5344823/how-can-i-listen-for-key-presses-within- java-swing-accross-all-components? – 2013-05-03 20:53:40

回答

1

JPanel延伸JComponent,繼承Container。您可以使用getComponents()。您會得到一個Component[]數組,您可以循環訪問併爲每個組件添加一個Component的子類,如Button,併爲每個組件添加相同的ActionListener。請參閱http://docs.oracle.com/javase/6/docs/api/java/awt/Component.html

+2

您可能需要使用遞歸來做到這一點,因爲組件可能嵌套在容器中。 – 2013-05-03 21:11:17

+0

@Hovercraft Full Of Eels [我知道(如果使用不正確,非常脆弱)非常簡單,可設置,基於字符串值,可以在飛行時生成參數](http://stackoverflow.com/questions/9007259/giving- jmenuitems名到其通的ActionListener/9007348#9007348) – mKorbel 2013-05-03 22:17:42

0

@cinhtau擁有正確的方法。由於沒有一個具有'addActionListener'方法的公共類型,這使得它變得更加困難。你必須檢查你想添加動作偵聽器的每個案例。

public static void addActionListenerToAll(Component parent, ActionListener listener) { 
    // add this component 
    if(parent instanceof AbstractButton) { 
     ((AbstractButton)parent).addActionListener(listener); 
    } 
    else if(parent instanceof JComboBox) { 
     ((JComboBox<?>)parent).addActionListener(listener); 
    } 
    // TODO, other components as needed 

    if(parent instanceof Container) { 
     // recursively map child components 
     Component[] comps = ((Container) parent).getComponents(); 
     for(Component c : comps) { 
      addActionListenerToAll(c, listener); 
     } 
    } 
} 
0

這就是我現在做的權利,它的工作

private void setActionListeners() { 
     for (Component c : this.getComponents()){ 
      if (c.getClass() == JMenuItem.class){ 
       JMenuItem mi = (JMenuItem) c; 
       mi.addActionListener(this); 
      } 
      if (c.getClass() == JCheckBoxMenuItem.class){ 
       JCheckBoxMenuItem cmi = (JCheckBoxMenuItem) c; 
       cmi.addActionListener(this); 
      } 
     } 
    } 
相關問題