-2

I have multiple JLabels in a JPanel. Whenever I change the text in one, it causes the other JLabels inside the JPanel to move. How to I lock them in place?

skorza
  • 21
  • 4
  • 2
    Welcome to Stack Overflow, as is, your question is unclear, a [mcve] might clarify what you mean. However I see you haven't taken the [tour], so go through it and learn [ask], then post the code of the MCVE by [edit]ing your question. This will lead to less confusion and more and better answers, if you don't follow above recommendations, your question might get closed and / or deleted and you getting banned from asking new questions in this site – Frakcool Jun 06 '17 at 18:53
  • 1
    In addition to the MCVE suggest by @Frakcool, provide ASCII art or a simple drawing of the *intended* layout of the GUI at minimum size, and if resizable, with more width and height. – Andrew Thompson Jun 07 '17 at 00:30

1 Answers1

-1

The approach really depends how you labels are positioned and what LayoutManager you are using.

JLabel by default will calculate its size mostly based on the label text and font size. If you are changing the text, then the JLabel size will change as well and thus make the layout manager to reposition the other labels.

Here is an example that uses FlowLayout and hard sets JLabel preferred size so that it wont change when its text changes. Other layout managers might choose to ignore the preferred size:

    JFrame frame = new JFrame();
    frame.getContentPane().setLayout( new FlowLayout() );

    JLabel l = new JLabel("text1");
    l.setPreferredSize( new Dimension( 50, (int)l.getPreferredSize().getHeight() ) );
    frame.getContentPane().add(l);

    frame.getContentPane().add( new JLabel("text2") );
    frame.getContentPane().add( new JLabel("text3") );

Here if you change text for l it wont shift the other 2 labels.

tsolakp
  • 5,858
  • 1
  • 22
  • 28
  • See [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/q/7229226/418556) (Yes.) – Andrew Thompson Jun 07 '17 at 03:46
  • Sorry but I don't agree with that rule. Especially with this example where user wants the JLabel to not change it's preferred size. In practice nobody is going to follow that rule 100%. – tsolakp Jun 07 '17 at 04:03