如何更改JLabel的字体大小以获取最大大小 [英] How to change the size of the font of a JLabel to take the maximum size

查看:173
本文介绍了如何更改JLabel的字体大小以获取最大大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在容器中有一个JLabel。
字体的默认大小非常小。
我希望JLabel的文本能够最大化。



我该怎么做?
感谢:)

解决方案

不是最漂亮的代码,但是下面的代码会为 JLabel 调用 label ,这样内部的文本就可以尽可能地适合内部而不会溢出标签:

  Font labelFont = label.getFont(); 
String 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));

基本上,代码看起来在 JLabel 占用使用 FontMetrics 对象,然后使用该信息来确定可以使用的最大字体大小,而不会溢出来自 JLabel 的文本。



上面的代码可以插入到 JFrame paint 它包含 JLabel ,或者当字体大小需要改变的时候调用的方法。



以下是上述代码的截图:

替代文字http://coobird.net/img/growing-text.png


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 ? Thanks :)

解决方案

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 http://coobird.net/img/growing-text.png

这篇关于如何更改JLabel的字体大小以获取最大大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆