I want to call JButton doClick() method to simulate a click action in Java

Java 8Object Oriented ProgrammingProgramming

Let us first set a JButton:

JButton btn = new JButton("DemoButton");

Now, attach action listener:

btn.addActionListener(new ClickListener());

If you have an ActionListener attached to your button it'll fire when you call the method doClick():

btn.doClick();

The following is an example to call JButton doClick() method to simulate a click action:

Example

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class SwingDemo {
   public static void main(final String args[]) {
      JButton btn = new JButton("DemoButton");
      btn.addActionListener(new ClickListener());
      JOptionPane.showMessageDialog(null, btn);
      btn.doClick();
   }
}
class ClickListener implements ActionListener {
   public void actionPerformed(ActionEvent e) {
      System.out.println("Clicked!");
   }
}

Output

On clicking “DemoButton” above, the following is the output visible:

raja
Published on 06-May-2019 10:51:25
Advertisements