Java Reference
In-Depth Information
Example 10•10: ColumnLayoutPane.java
package com.davidflanagan.examples.gui;
import java.awt.*;
import javax.swing.*;
public class ColumnLayoutPane extends JPanel {
public ColumnLayoutPane() {
// Get rid of the default layout manager.
// We'll arrange the components ourselves.
this.setLayout(new ColumnLayout(5, 5, 10, ColumnLayout.RIGHT));
// Create some buttons and set their sizes and positions explicitly
for(int i = 0; i < 6; i++) {
int pointsize = 8 + i*2;
JButton b = new JButton("Point size " + pointsize);
b.setFont(new Font("helvetica", Font.BOLD, pointsize));
this.add(b);
}
}
}
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 cov-
ered in this chapter. We'll see some examples of event handling using the old
model when we study applets (see Chapter 15, Applets ), where this model is still
sometimes used for backwards compatibility with old web browsers.
In Java 1.1 and later, the event-handling API is based on events and event listen-
ers. 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 event classes commonly used by AWT and Swing components.
The javax.swing.event package defines additional events used by Swing compo-
nents, 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 the X coordinate of the location of the mouse when the event occurred.
An EventListener is an object that is interested in being notified when an event of
a particular type occurs. An object that generates events (an event source , such as
a JButton component) maintains a list of listeners and provides methods that
allow listeners to be added to or removed from this list. When an event of the
appropriate type occurs, the event source notifies all registered event listeners. To
notify the listeners, it first creates an event object that describes the event and then
passes that event object to a method defined by the event listeners. The particular
Search WWH ::




Custom Search