Jump to Real's How-to Main page

Trigger a click on a Button

Regular AWT
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

 public class TestEvent extends Applet implements ActionListener {
   Button b2, b1;
   TextField t1;

   public void init() {
     setLayout(new FlowLayout());
     t1 = new TextField(30);
     b1 = new Button("Output");
     add(b1); add(t1);
     b2 = new Button("Fire event 1st button");
     add(b2);

     b1.addActionListener(this);
     b2.addActionListener(this);

     }

   public void actionPerformed(ActionEvent e) {
     if (e.getSource() == b1) {
       t1.setText("1st button clicked");
       }
     if (e.getSource() == b2) {
       //  from the b2 button, we creating an event to trigger a click
       //  on the b1 button
       ActionEvent ae = 
          new ActionEvent((Object)b1, ActionEvent.ACTION_PERFORMED, "");
       Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(ae);
       // b1.dispatchEvent(ae);  can be used too.
       }
     }
}

With Swing

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

 public class TestEventSwing extends JApplet implements ActionListener {
   JButton b1, b2;
   JTextField t1;

   public void init() {
     setLayout(new FlowLayout());
     t1 = new JTextField(30);
     b1 = new JButton("Output");
     add(b1); add(t1);
     b2 = new JButton("Fire event 1st button");
     add(b2);

     b1.addActionListener(this);
     b2.addActionListener(this);
     }

   public void actionPerformed(ActionEvent e) {
     if (e.getSource() == b1) {
       t1.setText("first button clicked");
       }
     if (e.getSource() == b2) {
       //  from the b2 button, we trigger a click on the b1 button.
       //  As an added bonus, a visual effect on b1 is visible!
       b1.doClick();
       }
     }
}

If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]