Search code examples
javaswingsizejlabel

How to determine the correct size to set a JLabel to if it's going to be initialized later to a known String


I have a JLabel which at creation is going to be blank. Later it's going to be initialized to a string "Hello World"

If I setText to "Hello World" later on, my whole layout gets screwed up (FWIW, I am using GridBagLayout).

This is the only way I found to avoid this issue.

JLabel tmp = new JLabel("Hello World");
Dimension d = tmp.getPreferredSize();

JLabel actual = new JLabel();
actual.setPreferredSize(d);

Is there no better way to do this?


Solution

  • What is the full context of the question? Why is it so important if the size changes? Does the change in size affect the grid of the GridBagLayout?

    Maybe you need a better design of the form so that a changing size in the text of the label does not affect the layout of the other components on the form? That is, maybe you need to nest different panels with different layout managers.

    For example you could use a panel with a CardLayout and then have each label as a card for the panel. Then instead of changing the text, you swap the labels. This way the panel will reserve the space for the largest card in the layout.