Trigger a click on a ButtonTag(s): AWT Swing


In this example, when we click on a Button, we trigger the action attached to the another Button.

Regular AWT (applet)

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 (japplet)

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, we have visual effect on b1!
       b1.doClick();
     }
   }
}

blog comments powered by Disqus