Event listeners – Java Basics #35

Introduction to event listeners

When it comes to GUI applications event listeners are important to learn. They allow you to see when user is clicking button, moving mouse, pushing keyboard keys etc. In order to “listen” to our users we need to write event procedures.

Let’s consider this simple listener:

From now on listener object will be noticed each time, when user clicks button.

A class which extends ActionListener has to have actionPerformed method inside:

When user clicks the JButton object, actionPerformed method is called. The listener source, like JButton, can have multiple listeners. Then, clicking the button runs actionPerformed from all of those listeners.

Event listener example

In order to practise event listeners we will create a simple application. The app will print a text after button click.

So when you ran this code this window appears:

java event listeners

After you click “Click me!” button the label will appear:

java event listeners Obviously, there are many more event listeners, but most of them works exactly the same way.

You can find more listeners at Oracle’s docs