gpt4 book ai didi

Java 将 ActionEvent 传递给父组件

转载 作者:行者123 更新时间:2023-12-01 12:53:11 24 4
gpt4 key购买 nike

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

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

我有我的主 Swing 应用程序类,其中包含 Swing 组件以及 JPanel 类。我想要做的是将 JPanel 类触发的 ActionEvents 分派(dispatch)到 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() 调用。

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

最佳答案

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

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

...
}

关于Java 将 ActionEvent 传递给父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24061227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com