How the pack() function behave when we explicitly set the location of the container?

帅比萌擦擦* 提交于 2019-12-25 06:38:39

问题


Here is the minimal example what problem I am facing in my main GUI design

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.BoxLayout;
class GuiTester
{

JFrame mainFrame = new JFrame();
JPanel panel = new JPanel();

GuiTester()
{

    JButton newButton = new JButton();
    JButton continueButton = new JButton();
    panel.setLayout(new BoxLayout( panel, BoxLayout.Y_AXIS));
    panel.add(newButton);
    panel.add(continueButton);
    panel.add(new JButton());
    panel.add(new JButton());
    panel.add(new JButton());
    mainFrame.getContentPane().add(panel);
    mainFrame.setLocationRelativeTo(null); // if I do it here then the display of window is little towards the right side down corner.
    mainFrame.pack();
    //mainFrame.setLocationRelativeTo(null) if I do it here instead of earlier than mainFrame.pack() it works great.
    mainFrame.setVisible(true);
}

public static void main(String[] args) {
    GuiTester gui = new GuiTester();
  }
}

So my question is that how pack() working differently when we do setLocationRelativeTo(null) prior to it and later to it?

And if we do setLocationRelativeTo(null) after pack() it works good.

Although the difference in this minimal example is not huge but in my actual working GUI this is creating a huge problem. Please explain.

EDIT My second question is that I have heard that it is recommended to call setVisible(true) or setReiszable(false) prior to pack(), why it is so?


回答1:


setLocationRelativeTo uses the current size of the window to make decisions about where it should be placed, since the window hasn't been sized yet, it's using 0x0, pack provides the initial size, so calling this first provides setLocationRelativeTo with the information it needs

You have to recognize that until a component is laid out (or in the case, until the is window packed or sized) it has no size.

For example...

mainFrame.setLocationRelativeTo(null);
mainFrame.pack();

This says, position the window, which is sized 0x0 to the center point of the screen, then use pack to provide an actual size

Where as...

mainFrame.pack();
mainFrame.setLocationRelativeTo(null);

Says, pack the frame to provide it with an initial size and the position it relative to the center of the screen, which takes into consideration windows size as calculated by pack



来源:https://stackoverflow.com/questions/31822144/how-the-pack-function-behave-when-we-explicitly-set-the-location-of-the-contai

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!