Responding to button clicks (Part 1)

Guest Posts Steven



In this article I'm going to explain how to make your program to respond when you click a button: in this first part I'm going to show how to do it with a function written directly to the button, that function would be:

btnName.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
     /*
     * things you want to happen
     * once you click the button
     */
   }
});


What we're going to do is make a text change once the button is clicked.

So 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 {

   private JPanel _panel;
   private JLabel lblChange;

   /**
   * Create the frame.
   */
   public exampleJFrame() {
      setVisible(true); //we make the window visible
      setResizable(false); // if write false, you won't be able to resize the window
      setTitle("Example"); //you set the title for the window
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      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();
      getContentPane().add(_panel);
      _panel.setLayout(null); // you set the Layout to null = Absolute Layout

      JButton btnClickMe = new JButton("Click Me!");
      btnClickMe.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            lblChange.setText("Button Clicked!");// you change the text of the label
         }
      });
      btnClickMe.setBounds(86, 84, 89, 23); // you set the size and position of the button in the JPanel
      _panel.add(btnClickMe); // you add the button to the panel

      lblChange = new JLabel("I'm going to change once you click the Button!");
      lblChange.setBounds(10, 24, 268, 14);
      _panel.add(lblChange);

   }

   public static void main(String[] args) {
      exampleJFrame example=new exampleJFrame();
   }
}


The result before clicking the button would be:

Image

After clicking the button:

frame2

As you can see the text changed after we clicked the button, we can do this with all the buttons we have, or we can also use an interface named "ActionListener", which implementation we'll see in the next article.