Swing Tutorial 3: Reacting to Button Clicks

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.

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:

textArea.append("Hello\n");

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.