AWT - catching click button event
Presented below is an example for catching button click event in AWT.
Code:
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.
}
}
}