I l@ve RuBoard |
![]() ![]() |
13.2 Painting Borders CorrectlyThe golden rule of creating borders is: "Never paint in the component's region." Here's a border that violates this rule: public class WrongBorder extends AbstractBorder { public WrongBorder( ) {} public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { g.setColor(Color.black); g.fillRect(x, y, width, height); // Bad } public boolean isBorderOpaque( ) { return true;} public Insets getBorderInsets(Component c) { return new Insets(20, 20, 20, 20); } } Look carefully at the paintBorder( ) method. The last four parameters passed in to the method can be used to calculate the total screen area of the component — including the border insets. We decided to paint our border by creating a single filled rectangle that fills the entire component space. While drawing the border, however, we painted over the underlying component and violated the golden rule. The correct approach is to obtain the insets of the border region and draw rectangles only in that space, as shown: public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Insets insets = getBorderInsets(c); g.setColor(Color.black); // Draw rectangles around the component, but do not draw // in the component area itself. g.fillRect(x, y, width, insets.top); g.fillRect(x, y, insets.left, height); g.fillRect(x+width-insets.right, y, insets.right, height); g.fillRect(x, y+height-insets.bottom, width, insets.bottom); } 13.2.1 The AbstractBorder ClassAbstractBorder is the superclass that all Swing borders extend. Although not mandatory, borders of your own design can also extend AbstractBorder. You will probably want to do this in order to take advantage of the utility methods it contains. AbstractBorder provides default implementations of the three methods of the Border interface. If you subclass AbstractBorder to create your own border, you should override at least the paintBorder( ) and getBorderInsets( ) methods. AbstractBorder also provides methods to calculate the area of the component being bordered and to simplify determining the orientation of a component (important for internationalization). 13.2.1.1 PropertyAbstractBorder has the property shown in Table 13-1. The default implementation of the borderOpaque property returns false. If you create a border that is opaque, you should override it and return true.
13.2.1.2 Constructor
13.2.1.3 Methods
Now that we're done with the preliminaries, let's look at the borders that Swing provides. ![]() |
I l@ve RuBoard |
![]() ![]() |