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?
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?
Source Code for Label - How to change Color and Font (in Netbeans)
taken from How to Use HTML in Swing Components
Just wanted to point out that the accepted answer has a couple of limitations (which I discovered when I tried to use it)
It is thus not suitable (without adaptation) for use in a repeated-call setting (eg a
ComponentResizedListener
, or a custom/modifiedLayoutManager
).The listed code effectively assumes a starting size of 10 pt but refers to the current font size and is thus suitable for calling once (to set the size of the font when the label is created). It would work better in a multi-call environment if it did
int newFontSize = (int) (widthRatio * 10);
rather thanint newFontSize = (int)(labelFont.getSize() * widthRatio);
Because it uses
new Font(labelFont.getName(), Font.PLAIN, fontSizeToUse))
to generate the new font, there is no support for Bolding, Italic or Color etc from the original font in the updated font. It would be more flexible if it made use oflabelFont.deriveFont
instead.The solution does not provide support for HTML label Text. (I know that was probably not ever an intended outcome of the answer code offered, but as I had an HTML-text
JLabel
on myJPanel
I formally discovered the limitation. TheFontMetrics.stringWidth()
calculates the text length as inclusive of the width of the html tags - ie as simply more text)I recommend looking at the answer to this SO question where trashgod's answer points to a number of different answers (including this one) to an almost identical question. On that page I will provide an additional answer that speeds up one of the other answers by a factor of 30-100.
Not the most pretty code, but the following will pick an appropriate font size for a
JLabel
calledlabel
such that the text inside will fit the interior as much as possible without overflowing the label:Basically, the code looks at how much space the text in the
JLabel
takes up by using theFontMetrics
object, and then uses that information to determine the largest font size that can be used without overflowing the text from theJLabel
.The above code can be inserted into perhaps the
paint
method of theJFrame
which holds theJLabel
, 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 http://coobird.net/img/growing-text.png