Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

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


1 Answer
Krantik Chavan

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:

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.