img
Compute the Paintable Area
When drawing to the surface of a component, you must be careful to restrict your output
to the area that is inside the border. Although Swing automatically clips any output that
will exceed the boundaries of a component, it is still possible to paint into the border, which
will then get overwritten when the border is drawn. To avoid this, you must compute the
paintable area of the component. This is the area defined by the current size of the component
minus the space used by the border. Therefore, before you paint to a component, you must
obtain the width of the border and then adjust your drawing accordingly.
To obtain the border width, call getInsets( ), shown here:
Insets getInsets( )
This method is defined by Container and overridden by JComponent. It returns an Insets
object that contains the dimensions of the border. The inset values can be obtained by using
these fields:
int top;
int bottom;
int left;
int right;
These values are then used to compute the drawing area given the width and the height of
the component. You can obtain the width and height of the component by calling getWidth( )
and getHeight( ) on the component. They are shown here:
int getWidth( )
int getHeight( )
By subtracting the value of the insets, you can compute the usable width and height of the
component.
A Paint Example
Here is a program that puts into action the preceding discussion. It creates a class called
PaintPanel that extends JPanel. The program then uses an object of that class to display lines
whose endpoints have been generated randomly. Sample output is shown in Figure 10-4.
FIGURE 29-4
Sample output from the PaintPanel program
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home