Search code examples
javaswinglayoutlayout-managerinsets

Insets.top , left, bottom, right all zero


This is a sample of the code that I am using to instantiate a JFrame:

public class TestFrame{
public static void main(String[] args){
    JFrame frame = new JFrame();
    Insets insets = frame.getInsets();
    frame.setSize(new Dimension(insets.right + insets.left + 400, insets.bottom + insets.top + 400));
    System.out.println(String.format("Top = %d \nBottom = %d \nLeft = %d \n Right
            = %d", insets.top, insets.bottom, insets.left, insets.right));

    frame.setResizable(false);
    frame.setVisible(true);
}
}

The frame is displaying fine but all of the insets seem to be equal to zero. I need to know the size of the title bar on top because I want a Content Pane of size 400x400 exactly.

I tested it on multiple platforms and the same thing happens on windows and on mac.

What am I doing wrong ?


Solution

    1. If you want your content pane to be precisely 400x400, then I would consider setting its preferredSize to 400x400 (although I don't like to force preferred size, on a content pane, it may be acceptable, in some cases).
    2. After setting that preferred size and before showing the frame, call pack() on the frame.

    This is the cleanest and easiest solution, and you don't have to care about border insets.