Chapter 2. Swing Mechanics
In this chapter:
Subpages: 1. JComponent properties, size, and positioning
2. Event handling and dispatching
5. AppContext service
6. Inside Timers & the TimerQueue
7. JavaBeans architecture
8. Fonts, Colors, Graphics and text
9. Using the Graphics clipping area
10. Graphics debugging
11. Painting and validation
12. Focus Management
13. Keyboard input, KeyStrokes, and Actions
2.1 JComponent properties, size, and positioning
All Swing components conform to the JavaBeans specification. In section 2.7 we will discuss this in detail. Among the five features a JavaBean is expected to support is a set of properties and associated accessor methods. A property is a global variable, and its accessor methods, if any, are normally of the form setPropertyname(), getPropertyname() or isPropertyname().
A property that has no event firing associated with a change in its value is called a simple property. A bound property is one for which PropertyChangeEvents are fired after it changes state. We can register PropertyChangeListeners to listen for PropertyChangeEvents through JComponent's addPropertyChangeListener() method. A constrained property is one for which PropertyChangeEvents are fired before a change in state occurs. We can register VetoableChangeListeners to listen for PropertyChangeEvents through JComponent's addVetoableChangeListener() method. A change can be vetoed in the event handling code of a VetoableChangeListener by throwing a PropertyVetoException. (There is only one Swing class with constrained properties: JInternalFrame).
PropertyChangeEvent's carry three pieces of information with them: name of the property, old value, and new value. Beans can use an instance of PropertyChangeSupport to manage the dispatching of PropertyChangeEvents corresponding to each bound property, to each registered listener. Similarly, an instance of VetoableChangeSupport can be used to manage the sending of all PropertyChangeEvents corresponding to each constrained property.
Swing introduces a new class called SwingPropertyChangeSupport (defined in javax.swing.event) which is a subclass of, and almost identical to, PropertyChangeSupport. The difference is that SwingPropertyChangeSupport has been built to be more efficient. It does this by sacrificing thread safety, which, as we will see later in this chapter, is not an issue in Swing if the multithreading guidelines are followed consistently (because all event processing should occur on only one thread--the event-dispatching thread). So if we are confident that our code has been constructed in a thread-safe mannar, we are encouraged to use this more efficent version, rather than PropertyChangeSupport.
Swing also introduces a new type of property which we will call a change property, for lack of a given name. We use ChangeListeners to listen for ChangeEvents that get fired when these properties change state. A ChangeEvent only carries one piece of information with it: the source of the event. For this reason, change properties are less powerful than bound or constrained properties, but they are more widespread. A JButton, for instance, sends change events whenever it is armed (pressed for the first time), pressed, and released (see chapter 5).
Another new property-like feature Swing introduces is the notion of client properties. These are basically key/value pairs stored in a Hashtable provided by each Swing component. This allows properties to be added and removed at run-time, and is often a convenient place to store data without having to build a separate subclass.
Client properties are bound properties: when a client property changes, a PropertyChangeEvent is dispatched to all registered PropertyChangeListeners. To add a property to a component's client properties Hashtable, we do the following:
To retrieve a client property:
myObject = myComponent.getClientProperty("myname");
To remove a client propery we can provide a null value:
For example, JDesktopPane uses a client property to control the outline dragging mode for JInternalFrames (this will work no matter which L&F is in use):
Five Swing components have special client properties that only the Metal L&F pays attention to. Briefly these are:
A String used to specify whether node relationships are displayed as angular connecting lines ("Angled"), horizontal lines defining cell boundaries ("Horizontal" -- default), or no lines at all ("None").
A Boolean value used to specify whether all sides of a JScrollbar will have an etched border (Boolean.FALSE -- default) or only the top and left edges (Boolean.TRUE).
A Boolean value used to specify whether the lower portion of a slider should be filled (Boolean.TRUE) or not (Boolean.FALSE -- default).
A Boolean value used to specify whether a toolbar button displays an etched border only when the mouse is within its bounds and no border if not (Boolean.TRUE), or always use an etched border (Boolean.FALSE -- default).
A Boolean value used to specify whether a very thin border is used (Boolean.TRUE) or the regular border is used (Boolean.FALSE -- default). As of Java 2 FCS this property is not used.
2.1.2 Size and positioning
Because JComponent extends java.awt.Container it inherits all the sizing and positioning functionality we are used to. We are encouraged to manage a component's preferred, minimum, and maximum sizes using the following methods:
The most comfortable size of a component. Used by most layout managers to size each component.
Used during layout to act as a lower bounds for a component's dimensions.
Used during layout to act as an upper bounds for a component's dimensions.
Each setXX()/getXX() method accepts/returns a Dimension instance. We will learn more about what these sizes mean in terms of each layout manager in chapter 4. Whether or not a layout manager pays attention to these sizes is solely based on that layout manager's implementation. It is perfectly feasible to construct a layout manager that simply ignores all of them, or pays attention to only one. The sizing of components in a container is layout-manager specific.
JComponent's setBounds() method can be used to assign a component both a size and a position within its parent container. This overloaded method can take either a Rectangle parameter (java.awt.Rectangle) or four int paramaters representing x-coordinate, y-coordinate, width, and height. For example, the following two are equivalent:
Rectangle rec = new Rectangle(120,120,300,300);
Note that setBounds() will not override any layout policies in effect due to a parent container's layout manager. For this reason a call to setBounds() may appear to have been ignored in some situations because it tried to do its job and was forced back to its original size by the layout manager (layout managers always have first crack at setting the size of a component).
setBounds() is commonly used to manage child components in containers with no layout manager (such as JLayeredPane, JDesktopPane, and JComponent itself). For instance, we normally use setBounds() when adding a JInternalFrame to a JDesktopPane.
A component's size can safely be queried in typical AWT style, such as:
int h = myComponent.getHeight();
int w = myComponent.getWidth();
Size can also be retrieved as a Rectangle or a Dimension instance:
Rectangle rec2 = myComponent.getBounds();
Dimension dim = myComponent.getSize();
Rectangle contains four publically accessible properties describing its location and size:
int recX = rec2.x;
int recY = rec2.y;
int recWidth = rec2.width;
int recHeight = rec2.height;
Dimension contains two publically accessible properties describing size:
int dimWidth = dim.width;
int dimHeight = dim.height;
The coordinates returned in the Rectangle instance using getBounds() represent a component's location within its parent. These coordinates can also be obtained using the getX() and getY() methods. Additionaly, we can set a component's position within its container using the setLocation(int x, int y) method.
JComponent also maintains an alignment. Horizontal and vertical alignments can be specified by float values between 0.0 and 1.0: 0.5 means center, closer to 0.0 means left or top, and closer to 1.0 means right or bottom. The corresponding JComponent methods are:
These values are only used in containers managed by BoxLayout and OverlayLayout.