Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the size of the font of a JLabel to take the maximum size

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?

like image 887
g123k Avatar asked Apr 26 '10 16:04

g123k


People also ask

How do I make my font bigger in Java?

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.

How do you change type size?

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.


2 Answers

label = new JLabel("A label"); label.setFont(new Font("Serif", Font.PLAIN, 14)); 

taken from How to Use HTML in Swing Components

like image 175
Asaf David Avatar answered Oct 06 '22 10:10

Asaf David


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:

alt text
(source: coobird.net)

like image 40
coobird Avatar answered Oct 06 '22 08:10

coobird