Responding to button clicks (Part 2)

Guest Posts Steven

In the first part we learned how to make your program respond when you click a button, but the way we did it is made for one button at a time. In this article I'm going to show you how to do it when have more buttons in your frame, to do this we need to make our JButtons global variables and also we need to use an interface named ActionListener.
You can learn more about this interface and how to use it here

Here's the code:

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class exampleJFrame extends JFrame implements ActionListener{

    private JPanel _panel;
    private JLabel lblChange;
     * buttons are global variables
    private JButton _hello,_goodbye;
     * Create the frame.
    public exampleJFrame() {
        setVisible(true); //we make the window visible
        setResizable(false); // if write false, you won't be able to re-size the window
        setTitle("Example"); //you set the title for the window
        setLocationRelativeTo(null); // you make the window appear at the center of the screen
        setSize(294,159); // you set the size of the window
        _panel = new JPanel();
        _panel.setLayout(null); // you set the Layout to null = Absolute Layout
        _hello = new JButton("Hello!");
        _hello.addActionListener(this); // the main frame is listening for a clicked button
        _hello.setBounds(23, 82, 89, 23); // you set the size and position of the button in the JPanel
        _panel.add(_hello); // you add the button to the panel
        lblChange = new JLabel("I'm going to change once you click a Button!");
        lblChange.setBounds(10, 24, 268, 14);
        _goodbye = new JButton("GoodBye!");
        _goodbye.setBounds(155, 82, 89, 23);
    public void actionPerformed(ActionEvent e) {
         * e.getSource(): it gets the source of the action
    public static void main(String[] args) {
        exampleJFrame example=new exampleJFrame();

That way depending on what button you click something is going to happen. You can use this wirh as many buttons as you have in your frame.