How to dynamically control auto-resize components in Java Swing

后端 未结 5 1837
耶瑟儿~
耶瑟儿~ 2020-12-15 22:25

Creating a new GUI in Java (1.8) Swing, I am searching for a way to override resize behavior of all my components.

Let me explain to you with some edited photos:

5条回答
  •  感情败类
    2020-12-15 23:01

    The important sequence is this:

                    frame.revalidate();
                    frame.pack();
                    frame.repaint();
    
    1. revalidate(): invalidates the components up to the nearest root afterwards the component hierarchy is validated starting from the nearest validate root.
    2. pack(): Causes the window to be sized to fit the preferred size and layouts of its subcomponents. The resulting width and hight of the window are automatically enlarged..
    3. repaints(): After all this recalculations, the repaint shows the components.

    Use this sequence after each series of changes, you have done in your code and want to see the results appearing on screen.

    I like the java.awt.GridBagLayout in combination with the java.awt.GridBagConstraints and I use this layout on all containers starting up from the content pane.

    If you add a container into an other container use a layout on each of them, otherwise the calculation fails because of a missing layout in the hierarchy.

提交回复
热议问题