27.1 Utility Classes


The utilities presented here are meant to be used with any part of your application. The constants from SwingConstants and static methods of the SwingUtilities class are used throughout the Swing source code and will probably be useful to you as well. You'll find a lot of these utilities fairly straightforward, and maybe even easy to reproduce with your own code. But try to familiarize yourself with these APIs; they're meant to keep you from reinventing those wheels with each new application you write.

27.1.1 The SwingUtilities Class

This class serves as a collection point for several methods common in more advanced GUI development projects. You probably won't use all of the methods in any one application, but some of the methods will doubtless come in handy from time to time. While the purpose of many of these methods is obvious from their signatures, here's a brief description of the utility calls at your disposal. For a more detailed discussion of the invokeLater( ) and invokeAndWait( ) methods, check out Chapter 28.

27.1.1.1 Constructor
public SwingUtilities( )

The constructor for SwingUtilities is public, but all of the public methods are static, so you do not need to create an instance.

27.1.1.2 Class methods
public static Rectangle calculateInnerArea (JComponent c, Rectangle r)

Calculate the position and size of the inner area (excluding the border) of c. The bounds are placed in r and r is returned. This method was introduced in SDK 1.4.

public static Rectangle[] computeDifference(Rectangle rectA, Rectangle rectB)

Return the regions in rectA that do not overlap with rectB. If rectA and rectB do not overlap at all, an empty array is returned. The number of rectangles returned depends on the nature of the intersection.

public static Rectangle computeIntersection(int x, int y, int width, int height, Rectangle dest)

Return the intersection of two rectangles (the first represented by (x, y, width, height)), without allocating a new rectangle. Instead, dest is modified to contain the intersection and then returned. This can provide a significant performance improvement over the similar methods available directly through the Rectangle class, if you need to do several such intersections.

public static int computeStringWidth(FontMetrics fm, String str)

Given a particular font's metrics, this method returns the pixel length of the string str.

public static Rectangle computeUnion(int x, int y, int width, int height, Rectangle dest)

Return the union of the rectangle represented by (x, y, width, height) and dest. As with computeIntersection( ), dest is modified and returned; no new Rectangle object is allocated.

public static MouseEvent convertMouseEvent(Component source, MouseEvent sourceEvent, Component destination)

Return a new MouseEvent, based on sourceEvent with the (x, y) coordinates translated to destination's coordinate system and the source of the event set as destination, provided destination is not null. If it is, source is set as the source for the new event. The actual translation of (x, y) is done with convertPoint( ).

public static Point convertPoint(Component source, Point aPoint, Component destination)
public static Point convertPoint(Component source, int x, int y, Component destination)

Convert a point from the source coordinate system to the destination coordinate system. If either source or destination is null, the other component's root component coordinate system is used. If both are null, the point is returned untranslated.

public static void convertPointFromScreen(Point p, Component c)

Convert a point on the screen, p, to a coordinate relative to the upper-left corner of the component, c.

public static void convertPointToScreen(Point p, Component c)

Opposite of the previous method, this method takes a point, p, relative to the upper-left corner of the component, c, and converts it to a coordinate on the screen. Such a conversion makes light work of tiling popup windows.

public static Rectangle convertRectangle(Component source, Rectangle aRectangle, Component destination)

Translate aRectangle from the source coordinate system to the destination coordinate system, following the same rules as convertPoint( ).

public static Component findFocusOwner(Component c)

Return the component at or below c that has the keyboard focus, if any. Because of security restrictions, this may not work for non-Swing components in applets. Note that this method has been deprecated as of SDK 1.4.1.

public static Accessible getAccessibleAt(Component c, Point p)

Return the Accessible component at point p (relative to the component c). If no such component exists, null is returned.

public static Accessible getAccessibleChild(Component c, int i)

Return the ith accessible child of component c that implements the Accessible interface.

public static int getAccessibleChildrenCount(Component c)

Return the number of accessible children in component c that implement the Accessible interface.

public static int getAccessibleIndexInParent(Component c)

For a given component c, this method returns its index in its accessible parent. If the component does not have an accessible parent, -1 is returned.

public static AccessibleStateSet getAccessibleStateSet(Component c)

Return the set of accessible states active for the component c.

public static Container getAncestorNamed(String name, Component comp)

Return the first container named name that contains component comp. null is returned if name cannot be found.

public static Container getAncestorOfClass(Class c, Component comp)

Similar to getAncestorNamed( ), this method returns the first container that is an instance of class c that contains component comp.

public static Component getDeepestComponentAt(Component parent, int x, int y)

Perform a recursive search through the component hierarchy starting at parent, and returns the last component containing the point (x, y). If parent is not a container, it is returned.

public static Rectangle getLocalBounds(Component aComponent)

Return a rectangle containing aComponent relative to aComponent, i.e., (0, 0, width, height).

public static Component getRoot(Component c)

Return the parent Window component, or the last applet to contain c if it is in a browser environment.

public static JRootPane getRootPane(Component c)

Find the root pane containing c. If no JRootPane is found containing c, null is returned.

public static void invokeAndWait(Runnable obj) throws InterruptedException, InvocationTargetException
public static void invokeLater(Runnable obj)

These methods take Runnable arguments and place them on the event queue to be executed after all pending events have been dispatched. The invokeLater( ) method essentially just pushes this Runnable onto the event queue. The invokeAndWait( ) method pushes it onto the queue and blocks until it has been dispatched.

JComponent is an example of a Swing component that uses this technique of delayed execution. It delays revalidation of any layout components until any other events pending have been handled by calling invokeLater( ). Some events rely on the location of their source to function properly (like tooltips), and moving the components before the event has been properly dispatched could cause confusion.

As mentioned earlier, Chapter 28 contains a more detailed discussion of these methods.

public static boolean isDescendingFrom(Component a, Component b)

Return true if component a descends from b in the component hierarchy.

public static boolean isEventDispatchThread( )

Return true if the current thread is the event-dispatching thread.

public static boolean isLeftMouseButton(MouseEvent anEvent)
public static boolean isMiddleMouseButton(MouseEvent anEvent)
public static boolean isRightMouseButton(MouseEvent anEvent)

These convenience methods return true if anEvent was performed with the left, middle, or right mouse button, respectively.

public static final boolean isRectangleContainingRectangle(Rectangle a, Rectangle b)

Return true if rectangle a completely contains rectangle b.

public static String layoutCompoundLabel(FontMetrics fm, String text, Icon icon, int verticalAlignment, int horizontalAlignment, int verticalTextPosition, int horizontalTextPosition, Rectangle viewR, Rectangle iconR, Rectangle textR, int textIconGap)

Lay out a label with text and an icon, using the font metrics, alignments, and text positions supplied relative to the viewR rectangle. If text cannot be contained in the label, it is truncated and "..." is appended. The resulting string is returned; textR and iconR are updated to contain the coordinates required to accomplish the desired layout.

public static void paintComponent(Graphics g, Component c, Container p, int x, int y, int w, int h)
public static void paintComponent(Graphics g, Component c, Container p, Rectangle r)

Paint the component c in an arbitrary graphics object g, bounded by the given rectangle, r. The container p is set as the new parent of c to stop the propagation of any validate( ) or repaint( ) calls to c. This is an easy way to rubber-stamp a component's image on a graphics area. For example, you might want to use this method in a tree or table cell renderer to draw "read-only" versions of components such as sliders. The image would look like a slider, but would just be an image, not a real component.

public static void updateComponentTreeUI(Component c)

Tell all components contained below c to update their current UI. This is useful if you allow the user to change the L&F of an application at runtime.

public static Window windowForComponent(Component aComponent)

This convenience method returns the Window object containing aComponent. If no containing window is found, null is returned. This method can be very handy when you're writing your own generalized (and occasionally modal) dialogs.

27.1.2 The SwingConstants Interface

This interface defines the location constants (shown in Table 27-1) that are used throughout the Swing package. Quite often, this interface is implemented by a component so that the constants appear as regular parts of the class for ease of use. (The AbstractButton, JLabel, and SwingUtilities classes are examples of such classes.)

Table 27-1. SwingConstants constants

Constant

Data type

Description

BOTTOM

int

Bottom location for vertical placement

CENTER

int

Center location or justification

EAST

int

East (right-side) location

HORIZONTAL

int

Horizontal position or orientation

LEADING

int

Leading edge for left-to-right or right-to-left text

LEFT

int

Left location or justification

NEXT1.4

int

The next direction in a sequence

NORTH

int

North (top, center) location

NORTH_EAST

int

Northeast (upper-right) location

NORTH_WEST

int

Northwest (upper-left) location

PREVIOUS1.4

int

The previous direction in a sequence

RIGHT

int

Right location or justification

SOUTH

int

South (bottom, center) location

SOUTH_EAST

int

Southeast (lower-right) location

SOUTH_WEST

int

Southwest (lower-left) location

TOP

int

Top location for vertical placement

TRAILING

int

Trailing edge for left-to-right or right-to-left text

VERTICAL

int

Vertical orientation

WEST

int

West (left-side) location, typically centered vertically

1.4since 1.4



Java Swing
Graphic Java 2: Mastering the Jfc, By Geary, 3Rd Edition, Volume 2: Swing
ISBN: 0130796670
EAN: 2147483647
Year: 2001
Pages: 289
Authors: David Geary

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net