by Dinesh Thakur Category: AWT and Applets

When you override the Container.insets () method, you are instructing the AWT to provide a margin around your container. The inset is used mostly by the Layout Manager to calculate sizing and positioning for contained objects. The Layout Manager will fit everything inside the insets you provide to it. The most common use of the inset space is to provide white space around a set of components to make them stand out as a group or just to provide more pleasing balance to a window.Remember that the insets indicate the distance from the border of the container to the contained objects. Effectively, you are setting the margins for your container. The space between the top, left, right, and bottom inset and the border of the container would be considered the margin.

For instance, Insets (20,10,10,1) would cause the Layout Manager to leave a 20 pixel top margin, 10 pixels on the left and right, and only 1 pixel at the bottom. We've started using a standard inset of 10 pixels for most of our containers, but you should follow your environment's guidelines for code of your own.

The method can be implemented very simply:

public Insets insets() {
   return new Insets(10,10,10,10);

This produces a new Insets object every time insets is called. If you want to enhance performance, and the specific constant insets will always be appropriate, you can instantiate a private object in the constructor and always return that object. Also, the four values allow you to vary the inset width on each of the top, left, bottom, and right.

You will often combine the inset with a simple border. In the container paint () method, you can call drawRect () to draw a simple pixel wide border around the container. The border is at the outside of the container, and contained components will be inset from the line by the active inset amount.

public void paint (Graphics g) {
    Dimension d = size();

Of course, just as on paper, you can draw in the margins of your container. You can use things other than drawRect to give the special effect you desire. A custom container might draw a shadow or other 3D effect that consumes all the space between the container border and it's inset. You are definitely not limited to lines, either. You can draw images, text, or any other graphic component in the margin of your container.

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles