【问题标题】:Java Passing ActionEvents to parent componentJava 将 ActionEvents 传递给父组件
【发布时间】:2014-07-26 12:11:06
【问题描述】:

首先抱歉,如果标题很简短,我已经考虑过但无法为我的问题提供足够简短的摘要。

我有一个由 JButton 组成的 JPanel 类。

我有我的主要 Swing 应用程序类,它具有 Swing 组件,以及 JPanel 类。我想要做的是将我的 JPanel 类触发的 ActionEvents 分派到我的 Swing 应用程序类进行处理。我已经在网络和论坛(包括这个)上搜索了示例,但似乎无法使其正常工作。

我的 JPanel 类:

public class NumericKB extends javax.swing.JPanel implements ActionListener {
    ...

    private void init() {
        ...
        JButton aButton = new JButton();
        aButton.addActionListener(this);

        JPanel aPanel= new JPanel();
        aPanel.add(aButton);
        ...
    }

    ...

    @Override
    public void actionPerformed(ActionEvent e) {   
        Component source = (Component) e.getSource();

        // recursively find the root Component in my main app class
        while (source.getParent() != null) {            
            source = source.getParent();
        }

        // once found, call the dispatch the current event to the root component
        source.dispatchEvent(e);
    }

    ...
}



我的主要应用类:

public class SimplePOS extends javax.swing.JFrame implements ActionListener {


    private void init() {
        getContentPane().add(new NumericKB());
        pack();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        ...

        // this is where I want to receive the ActionEvent fired from my NumericKB class
        // However, nothing happens

    }
}  


想写一个单独的 JPanel 类的原因是因为我想在其他应用程序中重用它。

另外,实际代码,我的主应用程序类有许多子组件,JPanel 类被添加到其中一个子组件中,因此递归 .getParent() 调用。

任何帮助将不胜感激。预先感谢!干杯。

【问题讨论】:

  • 你可以转发事件,如图这个可能的duplicate

标签: java swing jpanel actionevent dispatchevent


【解决方案1】:

您不能将事件重新抛出给父级,因为父级不支持传递ActionEvents。但是在您的情况下,您可以简单地检查您的组件是否具有操作支持并调用它。像这样的

public class NumericKB extends javax.swing.JPanel implements ActionListener {
  ...

  private void init() {
    ...
    JButton aButton = new JButton();
    aButton.addActionListener(this);

    JPanel aPanel= new JPanel();
    aPanel.add(aButton);
    ...
  }

  ...

  @Override
  public void actionPerformed(ActionEvent e) {   
    Component source = (Component) e.getSource();

    // recursively find the root Component in my main app class
    while (source.getParent() != null) {            
        source = source.getParent();
    }

    // once found, call the dispatch the current event to the root component
    if (source instanceof ActionListener) {
      ((ActionListener) source).actionPerformed(e);
    }
  }

...
}

【讨论】:

  • 感谢百万谢尔盖,我花了 3 个小时试图让它工作,你的一行解决了我的问题!只是好奇,什么是正确的方法,或者,什么时候使用 .dispatchEvent(ActionEvent) 调用是正确的?
  • 我从未使用过这种方法。我只知道它用于 Swing 中的内部事件处理。所以手动调用这个方法不是个好主意。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-04
  • 1970-01-01
  • 2018-08-03
  • 2019-02-17
  • 2013-01-01
  • 2020-08-21
  • 2019-04-02
相关资源
最近更新 更多