How can I draw a raised border around an AWT component?

Scott Stanchfield

The Component class has a getInsets() method that returns an Insets object. The Insets object has four public fields: top, bottom, left and right.

These insets define the area a container is reserving for its own use (such as drawing a decorative border). Layout managers must respect this area when positioning and sizing the contained components.

To create a raised, 3D border around whatever is contained within a Panel, define a subclass of panel and override its getInsets() and paint() methods. For example, you could define this border as being 5 pixels away from each edge of the container border, and reserving some extra room between it and the laid out components.

The class will look something like this:

  public class BorderPanel extends Panel {
    private static final Insets insets = 
                           new Insets(10,10,10,10);
    public Insets getInsets() {return insets;}
    public void paint(Graphics g) {
      Dimension size = getSize();
        5,5,size.width-11, size.height-11, true);

To create the panel, you define a static Insets object that represents the space to reserve. Because that space won't change, you used a single static final instance of it. You'll return this instance anytime a layout manager (or anyone else) calls getInsets().

You then define a paint() method that gets the size of the container into which it is painting, then draws a raised border within that space. You can use the above class as follows:

  Frame f = new Frame("Test");
  f.setLayout(new GridLayout(1,0));
  BorderPanel p = new BorderPanel();
  p.setLayout(new GridLayout(1,0));
  p.add(new Button("Hello"));