Chapter 9

Event Handling in UI

Java Swing, like any other UI library, is an event-driven framework. 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 write 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’ll learn how to handle events in Java GUI programs.

Introduction to Event Listeners

I’m sure you’ve tried to click the buttons of our calculator from Lesson 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 as Java interfaces and their methods have to be implemented in an object that will be listening to events.

This is how Java documentation describes the ...

Get Java® Programming 24-Hour Trainer now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.