How to change the size of the font of a JLabel to take the maximum size
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)
label = new JLabel("A label");
label.setFont(new Font("Serif", Font.PLAIN, 14));
taken from How to Use HTML in Swing Components
JLabel textLabel = new JLabel("<html><span style='font-size:20px'>"+Text+"</span></html>");
JLabel label = new JLabel("Hello World");
label.setFont(new Font("Calibri", Font.BOLD, 20));