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