Java Reference
In-Depth Information
Example 10•12: ScribblePane2.java (continued)
/**
* Clear the drawing area, using the component background color. This
* method works by requesting that the component be redrawn. Since this
* component does not have a paintComponent() method, nothing will be
* drawn. However, other parts of the component, such as borders or
* sub-components will be drawn correctly.
**/
public void clear() { repaint(); }
/** This field holds the current drawing color property */
Color color = Color.black;
/** This is the property "setter" method for the color property */
public void setColor(Color color) { this.color = color; }
/** This is the property "getter" method for the color property */
public Color getColor() { return color; }
}
Handling Component Events
The two previous examples have shown how to handle mouse and keyboard
events. These are low-level input events generated by the system and reported to
event listeners by code in the java.awt.Component class. Usually, when you are
building a GUI, you do not handle these low-level events yourself; instead, you
use predefined components to interpret the raw input events and generate higher-
level semantic events. For example, when the JButton component detects a low-
level mouse click and mouse release, it generates a higher-level
java.awt.event.ActionEvent to notify any interested listeners that the user
clicked on the button to activate it. Similarly, the JList component generates a
javax.swing.event.ListSelectionEvent when the user makes a selection from
the list.
Example 10-13 is a listing of ScribblePane3.java . This example extends Scrib-
blePane2 and adds a JButton and a JList to its user interface. The user can clear
the screen by clicking on the button and change the drawing color by selecting
from the list. You can see these new components in Figure 10-11. The example
demonstrates implementing the ActionListener and ListSelection Listener
interfaces to respond to the events generated by these Swing components.
When you run Example 10-13, notice it allows you to scribble on top of the JBut-
ton and JList components. Swing components are “lightweight” components,
which means that they are drawn directly within the window of the component
that contains them. This is quite different from the “heavyweight” AWT compo-
nents that use nested, but independent, windows.
Example 10•13: ScribblePane3.java
package com.davidflanagan.examples.gui;
import java.awt.*; // For Graphics object and colors
import javax.swing.*; // For JPanel component
import java.awt.event.*; // For ActionListener interface
import javax.swing.event.*; // For ListSelectionListener interface
Search WWH ::




Custom Search