How can I get JLabel to accurately predict how wide it should be?

I have a situation where the user enters String, and my code makes Jlabel for him and tries to center it on a fullscreen JFrame / Pane. My problem is to be able to accurately center it, I need to know its size.

I need a way to figure out how long (wide) the JLabel should be so that it fits the length of the string and nothing else. I tried using the preferredSize () method that the components have and it looked awful (I passed an empty value so that my user interface would determine the preferred size). I know how to determine the height that works (fontSize + 10px size is usually good), but I can't get the width.

I use absolute positioning (no LayoutManager).

thank

+3
source share
4 answers

I believe the actual width is equal getPreferredSize().getWidth()unless you set it in advance. Try to display your preferred size without setting it to zero. With MigLayout, when centering components, I usually use pref!to make the component as small as possible for all sizes and avoid wrapping, and then center it in a spacious parent container.

+5
source

If you are already using a font height + 10for height, you can easily use a string width + x.

You will use FontMetrics:

Graphics g;
FontMetrics met = g.getFontMetrics();
int height = met.getHeight();
int width = met.stringWidth(label.getText());
+6
source
+2

I highly recommend using LayoutManager for your GUI. You don’t know why you use absolute positioning, but this is a great example of the problems it causes.

FlowLayout It has a simple centering ability and many other layout manager support centers.

+1
source

All Articles