Search code examples
javaswingactionlistener

How to manually invoke actionPerformed in Java?


The method actionPerformed of class ActionListener is invoked when we click on a (let say) JButton. I want to run this method manually in a program. Is it possible? Here is an example:

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // do something
    }  
});

This actionPerformed is invoked when I click on button. Is there another way to call it manually using a line(s) of code in my program?


Solution

  • You can:

    • Call .doClick() on the button
    • Simply call actionPerformed(null) on the method ... difficult if the method is in an anonymous class
    • Call getActionListeners() on the JButton and iterate through the ActionListener[] array that is returned, calling each listener's actionPerformed method
    • Or have the listener itself call a method that the main program can call (my preferred way):
    public void someMethod() {
        // has code that the listener needs done
    }
    
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            someMethod();  // call it here in the listener
        }  
    });
    
    // in another part of the code, call the same method
    someMethod();