Event Handling

In the previous section on layout management, there were a number of examples that arranged JButton components in interesting ways. If you ran the examples, however, you probably noticed that nothing interesting happened when you clicked on the buttons. The fourth step in creating a GUI is hooking up the event handling that makes components respond to user input. As of Java 1.1 and later, AWT and Swing components use the event-handling API defined by the JavaBeans component model. Prior to Java 1.1, the AWT used a different API that is not covered in this chapter. We’ll see some examples of event handling using the old model when we study applets (see Chapter 16), where this model is still sometimes used for backward compatibility with old web browsers.

In Java 1.1 and later, the event-handling API is based on events and event listeners. Like everything else in Java, events are objects. An event object is an instance of a class that extends java.util.EventObject. The java.awt.event package defines a number of event classes commonly used by AWT and Swing components. The javax.swing.event package defines additional events used by Swing components, but not by AWT components. And the java.beans package defines a couple of JavaBeans event classes also used by Swing components. Event classes usually define methods (or fields) that provide details about the event that occurred. For example, the java.awt.event.MouseEvent class defines a getX( ) method that returns ...

Get Java Examples in a Nutshell, 3rd 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.