How can I draw a raised border around an AWT component?
Created May 7, 2012
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();
g.setColor(getBackground());
g.draw3DRect(
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));
f.setBackground(Color.lightGray);
BorderPanel p = new BorderPanel();
p.setLayout(new GridLayout(1,0));
p.add(new Button("Hello"));
f.add(p);
f.setVisible(true);
f.pack();