【问题标题】:Call actionPerformed of a JTextField using its object使用 JTextField 的对象调用 actionPerformed
【发布时间】:2023-03-08 19:46:01
【问题描述】:

我有一个名为 SearchBoxjavax.swing.JTextField 带有一个 actionPerformed 事件。

public void SearchBoxActionPerformed(java.awt.event.ActionEvent evt){
     //TODO
}

我想要做的是通过传递JTextField 对象作为参数从不同类中的另一个方法调用上述方法。

import javax.swing.JTextField;

public class Program {

    public static synchronized void QuickSearchResults(JTextField textBox) {
        /*
         * I want to call ActionPerformed method of textBox if it has any.
         */
    }
}

请注意,不能直接调用方法名称。如果 我传递了 3 个不同的 JTextField 对象,相关的 ActionPerformed 方法应该被调用。

有没有办法做到这一点?我已经试过了,

textBox.getActions();
textBox.getActionListeners();

但它并不顺利,现在我又回到了第一方。

感谢您的建议!

【问题讨论】:

  • 你不能从另一个类调用私有方法。要接收ActionEvent JTextField 必须使用addActionListener 添加ActionListener
  • @JaySmith ActionEvent 在我按下回车键时运行良好。我刚刚添加了摘要。
  • 即使我将方法设为Public,我如何使用JTextField 对象来调用它?
  • 如果你使用JTextField,你只能调用它的方法。
  • 你可以从你添加到jtextfield的actionPerformed中的actionPerformed调用SearchBoxActionPerformed方法

标签: java swing jtextfield actionevent javax


【解决方案1】:

我已经找到了实现这一点的方法,但肯定不是最好的。

public static synchronized void QuickSearchResults(JTextField textBox) {
    ActionListener actions[] = textBox.getActionListeners();
    for (ActionListener x : actions) {
        x.actionPerformed(null);
    }
}

在这种情况下,只有ActionListeners 被调用,但所有这些都已使用addActionListener(ActionListener l) 添加到JTextField

正如我上面所说,这可能不是最好的方法,但可以解决问题。

【讨论】:

  • 不,它不会,它只会触发 ActionListeners(我在发布之前检查了源代码)事实上,你在循环中所做的就是我对 postActionEvent 所做的?-传递 null我会建议 ActionEvent,因为我们都习惯于获取非空值
  • @MadProgrammer 它确实调用了大部分EventListeners。尝试使用addFocusListener(FocusListener l)addKeyListener(KeyListener l) 添加更多事件。喜欢keyReleasedfocusLost 事件...
  • 不,它没有,它所做的只是调用fireActionPerformed,也许你在想postEvent?为什么会触发焦点丢失事件?
  • 所以,我创建了一个带有字段添加按钮的测试,我附加了一个 ActionListener、MouseListener、FocusListener 和 KeyListener,我在单击按钮时调用了 postActionEvent ...并且...只有 ActionListener收到通知
【解决方案2】:

JTextField#postActionEvent 将触发字段ActionListeners,这就是我假设您正在尝试做的事情

public class Program {

    public static synchronized void QuickSearchResults(JTextField textBox) {
        textBox.postActionEvent();
    }
}

【讨论】:

  • 这很好。但这会调用与 JTextField 连接的所有 actionEvent。有没有办法调用特定的?
  • 并不是它应该如何工作,我的意思是,如何识别您感兴趣的特定听众?您可以查看 getActionListeners,但您仍然必须生成自己的 ActionEvent。如果没有更多信息,我建议调查 Action API
  • 这是最简单的方法。
【解决方案3】:

使用此代码

public static synchronized void QuickSearchResults(JTextField textBox) {
    /*
     * I want to call ActionPerformed method of textBox if it has any.
     */
    textBox.addActionListener(e->{
        //Do what you want
    });
}

【讨论】:

  • 添加一个新的ActionListener 不会有帮助。因为 actionPerformed 方法中的代码会从 JtextFieldJtextField 不同。我需要调用JtextField传递的具体actionPerformed事件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-22
  • 1970-01-01
  • 2013-03-05
  • 1970-01-01
  • 1970-01-01
  • 2017-05-05
相关资源
最近更新 更多