How does the pack () function work when we explicitly set the container's location?

Here is a minimal example of what problems I am facing in my basic graphic 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, how pack()

does it work differently when we do setLocationRelativeTo(null)

before it and then before it?

And if we do setLocationRelativeTo(null)

after pack()

, it works well.

While the difference in this minimal example isn't huge, it poses a huge problem in my working GUI. Explain, please.

EDIT . Second question: I heard that it is recommended to call before package () setVisible(true)

or setReiszable(false)

why is it so?

0


source to share


1 answer


setLocationRelativeTo

uses the current window size to make decisions about where it should be placed, since the window hasn't been set yet, it using 0x0

, pack

provides the initial size, so calling this first provides the setLocationRelativeTo

information it needs

You have to admit that until a component is laid out (or in the case that it is not boxed or sized) it is not sized.

For example...

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

      



This tells the position of the window, which 0x0

is sized at the center point of the screen, then use pack

to ensure the actual size

Where how...

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

      

Says a pack

frame to give it an initial size and position in relation to the center of the screen, which takes into account the window size calculatedpack

+4


source







All Articles