How to change the size of the font of a JLabel to take the maximum size(如何更改 JLabel 的字体大小以获取最大大小)
问题描述
我在容器中有一个 JLabel
.字体的默认大小非常小.我希望 JLabel
的文本采用最大尺寸.
我该怎么做?
不是最漂亮的代码,但下面将为名为 label
的 JLabel
选择合适的字体大小> 使得里面的文字尽可能的贴合内部而不溢出标签:
字体 labelFont = label.getFont();字符串 labelText = label.getText();int stringWidth = label.getFontMetrics(labelFont).stringWidth(labelText);int componentWidth = label.getWidth();//找出字体的宽度可以增长多少.double widthRatio = (double)componentWidth/(double)stringWidth;int newFontSize = (int)(labelFont.getSize() * widthRatio);int componentHeight = label.getHeight();//选择一个新的字体大小,使其不会大于标签的高度.int fontSizeToUse = Math.min(newFontSize, componentHeight);//将标签的字体大小设置为新确定的大小.label.setFont(new Font(labelFont.getName(), Font.PLAIN, fontSizeToUse));
基本上,代码会查看
(来源:coobird.net)
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?
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)
这篇关于如何更改 JLabel 的字体大小以获取最大大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何更改 JLabel 的字体大小以获取最大大小


- 未找到/usr/local/lib 中的库 2022-01-01
- 转换 ldap 日期 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 获取数字的最后一位 2022-01-01