Swing Tutorial 3: Reacting to Button Clicks

Guest Posts ljc1999

In this third Swing tutorial we're going to add some text to our JTextArea when we click the button.

Its quite simple to do this, we need to add an Action Listener to the button. An Action Listener basically listens to the button, when the button is clicked it tells the Action Listener and we can program the Action Listener to do anything when it knows that the button has been clicked.

To do this add this code to your "MainFrame" class:

btn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {

You need to import Action Listener and Action Event, CTRL + SHIFT + O(CMD + SHIFT + O on Mac).

As you can see we add an Action Listener to the button we created in the previous tutorial, called "btn", then we created a new Action Listener to add to it. Inside the Action Listener is a method, called actionPerformed, inside this method we can tell the Action Listener what to do when the button is clicked.

So to complete our goal of adding text to our JTextArea every time the button is clicked lets add 1 line of code to the actionPerformed method:


We type the name of our JTextArea, in my case "textArea", and append a string "Hello\n", you can change this, the "\n" in the string creates a new line after the text so it doesn't all go on the same line.

If we run this now we can type in our JTextArea and when we click the button it adds "Hello" to it.


import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;

public class MainFrame extends JFrame {
    private JTextArea textArea;
    private JButton btn;
    public MainFrame() {
        super("Hello World");
        setSize(600, 500);
        setLayout(new BorderLayout());
        textArea = new JTextArea();
        btn = new JButton("Click Me!");
        add(textArea, BorderLayout.CENTER);
        add(btn, BorderLayout.SOUTH);
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {