|
| | Every component has a set of insets. Insets specify the widths of the
component's margins. Insets include:
- top inset
- left inset
- bottom inset
- right inset
For example, a frame's insets include a top inset
that compensates for the frame's titlebar, and insets all around that
compensate for the border (which we can use to resize the frame).
A panel contained within a frame has its own insets. Indeed, any
component has its own insets. Usually, however, you only have to
worry about insets for containers -- unless you're designing a new GUI
component.
Layout managers are supposed to respect a container's insets and never lay
out a component in the inset margins. The layout managers supplied with
the JDK all respect this. If you write a layout manager, you
should write it to respect insets, too.
Note: It seems that the use of insets is now deprecated, in favor of
borders. We'll discuss borders, which are much richer and provide much
greater flexibility,
shortly.
Here's an example that shows how to set insets for a container:
package swingExamples;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
class BorderButtonsInsetsPanel extends JPanel
{
public BorderButtonsInsetsPanel()
{
setBackground(Color.GREEN);
setLayout(new BorderLayout());
add(m_north, BorderLayout.NORTH);
add(m_south, BorderLayout.SOUTH);
add(m_east, BorderLayout.EAST);
add(m_west, BorderLayout.WEST);
add(m_center, BorderLayout.CENTER);
}
// Override this method to specify the panel's
// insets (top, left, bottom, right).
public Insets getInsets()
{
return new Insets(5, 10, 15, 20);
}
////////////// Data //////////////////
private JButton m_north = new JButton("North");
private JButton m_south = new JButton("South");
private JButton m_east = new JButton("East");
private JButton m_west = new JButton("West");
private JButton m_center = new JButton("Center");
}
class BorderButtonsInsetsFrame extends JFrame
{
public BorderButtonsInsetsFrame()
{
setTitle("BorderButtonsInsets");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.add( new BorderButtonsInsetsPanel() );
}
}
public class BorderButtonsInsets
{
public static void main(String[] args)
{
BorderButtonsInsetsFrame frame =
new BorderButtonsInsetsFrame();
frame.setVisible(true);
}
}
|
which produces the following interesting effect:

Note that the inset margins do not have to be the same all the way around.
I've emphasized this in the above example, which makes it look a little
strange. However, this can be used to advantage in some situations to
improve the look of a GUI application.
|