简体   繁体   English

每当我更改同一 JPanel 中其他 JLabels 的文本时,如何停止 JLabels 在 JPanel 内更改的位置?

[英]How do I stop the position of JLabels changing inside a JPanel whenever I change the text of other JLabels in the same JPanel?

I have multiple JLabels in a JPanel.我在 JPanel 中有多个 JLabel。 Whenever I change the text in one, it causes the other JLabels inside the JPanel to move.每当我更改一个文本时,它会导致 JPanel 内的其他 JLabel 移动。 How to I lock them in place?如何将它们锁定到位?

The approach really depends how you labels are positioned and what LayoutManager you are using.该方法实际上取决于您如何定位标签以及您使用的是什么 LayoutManager。

JLabel by default will calculate its size mostly based on the label text and font size.默认情况下,JLabel 将主要根据标签文本和字体大小计算其大小。 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.如果您要更改文本,则 JLabel 大小也会更改,从而使布局管理器重新定位其他标签。

Here is an example that uses FlowLayout and hard sets JLabel preferred size so that it wont change when its text changes.这是一个使用 FlowLayout 并硬设置 JLabel 首选大小的示例,以便在其文本更改时不会更改。 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.在这里,如果您更改l文本,它不会移动其他 2 个标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM