Lesson 9Event Handling in Swing GUI

Java Swing, like any other UI library, is event-driven. When a user interacts with a GUI program (such as by clicking a button or pressing a key) a Java Swing program receives an event that can initiate an appropriate reaction.

If you wrote the code to react to a particular event, this code will be invoked. If you haven’t written such code, the event will be fired anyway, but the program won’t respond to it. In this lesson you learn how to handle events in Java GUI programs.

Introduction to Event Listeners

I’m sure you’ve tried to click the buttons of the calculator from  Chapter 8, but they were not ready to respond to your actions yet. Swing widgets can process various events, or in the programmers’ jargon can listen to events. To listen to events, a program has to register window components with Java classes called listeners.

You should have components listen only to the events they are interested in. For example, when a person clicks a button, it’s not important where exactly the mouse pointer is as long as it is on the button’s surface. That’s why you do not need to register the button with MouseMotionListener. On the other hand, this listener comes in handy for all kinds of drawing programs.

To process button clicks, Swing provides ActionListener. All listeners are declared Java interfaces and their methods have to be implemented in an object that listens to events.

This is how Java documentation describes the ActionListener interface: ...

Get Java Programming 24-Hour Trainer, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.