Call button doClick method to simulate a click action in Java
Description
The following code shows how to call button doClick method to simulate a click action.
Example
// w w w . j a va2 s .c om
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main extends JFrame {
private JButton button1 = new JButton("Click Me!");
public static void main(String[] args) {
new Main();
}
public Main() {
this.setSize(275, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ClickListener cl = new ClickListener();
button1.addActionListener(cl);
button1.doClick();
this.add(button1);
this.setVisible(true);
}
private class ClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
button1.setText("clicked");
}
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »