【问题标题】:Add listener to all objects in a JPanel将侦听器添加到 JPanel 中的所有对象
【发布时间】:2013-04-28 08:31:12
【问题描述】:

我有一个 JPanel,其中包含许多对象,并且可以执行一个主要操作:计算。有一个按钮可以执行此操作,还有一个 JTextField 和其他用户可能希望在其中按 enter 的组件。例如,如果您从 JComboBox 中选择某些内容并按 enter,则将进行计算。有没有一种简单的方法可以将这样的侦听器添加到 JPanel 的所有内容中,而不是将 actionListeners 添加到每个单独的组件中?

【问题讨论】:

标签: java swing jpanel listeners


【解决方案1】:

JPanel 扩展 JComponent,继承 Container。您可以使用getComponents()。你得到一个Component[] 数组,你可以循环并为每个组件添加它,这是Component 的子类,就像Button,并为每个组件添加相同的ActionListener。见http://docs.oracle.com/javase/6/docs/api/java/awt/Component.html

【讨论】:

【解决方案2】:

@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 );
        }
    }
}

【讨论】:

    【解决方案3】:

    这就是我现在所做的,它奏效了

    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);
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      • 1970-01-01
      • 2012-09-09
      • 2016-10-19
      • 2018-12-10
      • 1970-01-01
      • 2013-02-17
      相关资源
      最近更新 更多