How do you stop a JLabel changing its size when its text changes?

≯℡__Kan透↙ 提交于 2019-12-04 10:12:29

You can fix the size of the labels by setting the minimum, prefered and maximum size:

label.setMinimumSize(width, height);
label.setPreferedSize(width, height);
label.setMaximumSize(width, height);

Also make sure to set the GridBagConstraints#fill to NONE, although I am not sure if that is still neccessary (I think it is).

EDIT: btw, to get rid of those nasty dashed lines around the focused Component, you can just set it to be not focusable:

slider.setFocusable(false);

The set-the-preferred-size solution works only if you don't have the components horizontally fill their bag in the GridBagLayout.

Another solution is to remove the weight you have placed on components in that column of your GridBagLayout. You can then control the column width manually. An easy way to do so (at design time) is to place a JLabel in the column with zero height and the specific width you desire.

Why is this? You need to dig into how GridBagLayout works:

The GridBagLayout sizes its columns based on the space required, and then uses the weights to allocate the "left over" space so that the resulting column widths then add up to the total width of the panel. The space required for each column is computed by finding the widest of the components in that column.

The space required for each component is determined by asking it what width it would prefer. In your case, a JLabel with "0" is smaller than a JLabel with "-12" and so the column is changing size.

The left over space is allocated based on the horizontal weights assigned to components in each column. The weights are totaled and percentages for each column are determined based on that column's percent of the total.

The column size is determined based on the space required PLUS the left over space. So, if all your components in the column have no weight then you'll not get any left over space, and hence not get dynamic changes.

A third solution is to just not use GridBagLayout.

Explicitely set the preferred size of your labels using JLabel#setPreferredSize(Dimension).

This way, you lock the size of the component, and tell the layout manager not to resize it.

label.setPreferredSize(new Dimension(width, height));

This was only way i could find to make it work. Setting a Minimum and/or a Maximum didn't do anything for me. Also, for me on java 8 i needed to use a Dimension, or there was no change to the previous, inappropriate sizes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!