How do I get a JLabel to accurately predict how wide it should be?
I have a situation where a user enters a String and my code makes a Jlabel fo开发者_如何学Gor it and attempts to center it on a full screen JFrame/Pane. My problem is, to be able to accurately center it, I need to know its dimensions.
I need a way to figure out how long (wide) the JLabel should be so that it accomodates the length of the string and nothing more. I tried using the preferredSize() method that components have and it looked horrible (I passed a null value to let my UI determine the preferredSize). I know how to figure out the height that works (the size of the fontSize + 10px is usually good) but I can't get the width.
I am using absolute positioning (no LayoutManager).
Thanks
I believe the actual width comes from getPreferredSize().getWidth()
if you don't set it beforehand. Try outputting the preferred size without setting it to null. With MigLayout when centering components, I normally use pref!
to make the component as small as possible for all sizes and avoid wrapping, and then center it in the spacious parent container.
If you are already using the font height + 10
for height, you can easily use the string width + x
.
You will use FontMetrics
:
Graphics g;
FontMetrics met = g.getFontMetrics();
int height = met.getHeight();
int width = met.stringWidth(label.getText());
by using some of LayoutManagers check this How to determine the length of a graphic string?
I strongly suggesting using a LayoutManager for your GUI. Not sure why you are using absolute positioning, but this is a perfect example of the problems it causes.
FlowLayout
has a simple centering ability and many other layout manager support centering as well.
精彩评论