I have a JLabel
in a Container. The defaut size of the font is very small. I would like that the text of the JLabel
to take the maximum size.
How can I do that?
You can't actually change the size of an existing Font object. The best way to achieve a similar effect is to use the deriveFont(size) method to create a new almost identical Font that is a different size. Save this answer.
To make your font size smaller or larger: On your device, open the Settings app. Search and select Font size. To change your preferred font size, move the slider left or right.
label = new JLabel("A label"); label.setFont(new Font("Serif", Font.PLAIN, 14));
taken from How to Use HTML in Swing Components
Not the most pretty code, but the following will pick an appropriate font size for a JLabel
called label
such that the text inside will fit the interior as much as possible without overflowing the label:
Font labelFont = label.getFont(); String labelText = label.getText(); int stringWidth = label.getFontMetrics(labelFont).stringWidth(labelText); int componentWidth = label.getWidth(); // Find out how much the font can grow in width. double widthRatio = (double)componentWidth / (double)stringWidth; int newFontSize = (int)(labelFont.getSize() * widthRatio); int componentHeight = label.getHeight(); // Pick a new font size so it will not be larger than the height of label. int fontSizeToUse = Math.min(newFontSize, componentHeight); // Set the label's font size to the newly determined size. label.setFont(new Font(labelFont.getName(), Font.PLAIN, fontSizeToUse));
Basically, the code looks at how much space the text in the JLabel
takes up by using the FontMetrics
object, and then uses that information to determine the largest font size that can be used without overflowing the text from the JLabel
.
The above code can be inserted into perhaps the paint
method of the JFrame
which holds the JLabel
, or some method which will be invoked when the font size needs to be changed.
The following is an screenshot of the above code in action:
(source: coobird.net)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With