【问题标题】:Resize JLabel text size with collections in Java Swing在 Java Swing 中使用集合调整 JLabel 文本大小
【发布时间】:2017-12-31 09:40:17
【问题描述】:

我正在尝试使用此代码更改我的 JLabel 文本大小:

my_font = my_label.getFont();

my_font = my_font.deriveFont(
        Collections.singletonMap(
                TextAttribute.SIZE, TextAttribute.20));

这一行有一个编译器警告:

TextAttribute.20;

此代码完美运行并更改了文本粗细:

font_bold = numero_fattura.getFont();

font_bold = font_bold.deriveFont(
        Collections.singletonMap(
                TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD));

问题:如何使用相同的代码更改文字大小?

【问题讨论】:

  • 非常感谢!我是这个网站的新手,我正在学习。这条评论很有用。

标签: java swing text size jlabel


【解决方案1】:

据我了解您的问题,您的答案类似于下面所说的线程第一个答案,只需点击此链接 -

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

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));

希望对您有所帮助,谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 2017-06-04
    • 2021-07-20
    相关资源
    最近更新 更多