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


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:

Updated on: 30-Jul-2019

848 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements