javaswingjtextfieldactioneventjavax

Call actionPerformed of a JTextField using its object


I have a javax.swing.JTextField named SearchBox with an actionPerformed Event.

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

What I want to do is to call the above method from another method in a different class by passing the JTextField object as an argument.

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.
         */
    }
}

Please note that calling the method name directly is not an option. If I pass 3 different JTextField objects, the relevant ActionPerformed methods should be called.

Is there a way to achieve this? I already tried using,

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

but it didn't go well, and now I'm back in square one.

Thanks in advice!


Solution

  • JTextField#postActionEvent will trigger the fields ActionListeners, which is what I assume you're trying to do

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