开发者

Java Swing set "actual" Frame size (inside)

I have a JFrame which contains just one JPanel. I have tried setting the Panel's size and packing the frame, but that has no effect.

If I set the JFrame's size, it will change the size so it includes the title bar and borders. How do I set the "actual size" so it doesn't include the title bar and borders?

Example:

开发者_如何学运维

Java Swing set "actual" Frame size (inside)

Thanks in advance, guys


You could set the contentPane's preferredSize and call pack on the JFrame, but in general it's usually best to let components size themselves based on their preferred sizes as determined by their layout managers.


This is an example of setting JPanel's size and packing the frame:

JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(200, 200));
frame.add(panel);
frame.pack();
frame.setVisible(true);

Did you try something like this?


If you set the preferred size of the JPanel then the JFrame's pack() method will respect it.


Use the .getInsets method on JFrame which gives you the dimensions of the sizes around the non-client area.

Then add it up to your wanted size, and set the size using setSize.


If you want to get Frame border then first use pack on your frame and after that get Frame Insets like in this code bellow:

frame.pack();
Insets insets = frame.getInsets();
int frameLeftBorder = insets.left;
int frameRightBorder = insets.right;
int frameTopBorder = insets.top;
int frameBottomBorder = insets.bottom;

Is better to use the pack method right after your setResizable(boolean) method, because resizable for some reason changes your frame borders, but if you dont use resize method then use pack method right on the start of frame constructor.


Setting the actual size of the usable space in JFrame could be done through setting the preferred size of the container in createComponents(Container container) method. Done in this way, you skip setting the size of the whole JFrame through setPreferredSize(new Dimension (width, length) in the run() method. So, the code will look like this:

@Override
public void run() {
    JFrame frame = new JFrame();
    // other code ...
    this.createCompoents(frame.getContentPane());
}

private void createCompoents(Container container) {
   // other code ...
   container.setPreferredSize(new Dimension(width, length));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜