2013-05-03 79 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); 
      } 
     } 
    } 
相关问题