What is a Swing Border?

Scott Stanchfield

A Swing Border is a decoration that defines a reserved space around a component, and paints within that space.

The Border interface looks like

public interface Border {
  void paintBorder(Component c, Graphics g, 
                   int x, int y, int width, int height);
  Insets getBorderInsets(Component c);
  boolean isBorderOpaque();
}

Because it's an interface, anyone can define a custom border decoration around a component. All you need to do is implement the Border interface in a class, describe the space it takes (the insets), whether or not it's opaque (meaning you guarantee you'll fill in all pixels in the insets space) and the painting instructions.

Swing defines several useful Borders in package javax.swing.border, which you can attach to any Swing component. Some common borders are:

BevelBorder
Draws a "raised" or "lowered" looking 3D sloped border around a component
CompoundBorder
Allows you to nest one border inside another
EmptyBorder
Doesn't paint anything, but reserves space, leaving empty room around a component
EtchedBorder
Draws a "lowered" or "raised" 3D etched line around a component
LineBorder
Draws a simple line around a component
MatteBorder
Tiles an image around a component (cropping at the insets)
SoftBevelBorder
Like BevelBorder, but has rounded edges
TitledBorder
Draws a title on top of another border (or a title with a line border if you don't specify a border yourself)

You can use the BorderFactory class to create borders. BorderFactory will cache borders to reduce the number of objects you create for your GUI. For example:

Border b = BorderFactory.createRaisedBevelBorder();

Once you've created a Border, you attach it to a Swing component using the setBorder method:

c.setBorder(b);

When the component is painting itself, it checks to see if it has an attached border. If so, it asks the border to paint itself.

If the component is a container (like a JPanel) that has a layout manager, the layout manager is required to respect the container's insets. If the component has a Border, the insets are determined by the Border. When the layout manager asks the component for its insets, the component delegates the request to the Border. This allows the border to reserve space for decoration.

If the component is contained within a layout manager that respects preferred size, the preferred size calculation includes any insets specified by a border. For example, if the component is a JButton, which usually has a Border set automatically, the JButton will calculate a preferred size that is big enough for the button's text, and the border around that text.

Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact