使用 Java Swing 中的集合调整 JLabel 文本大小

Resize JLabel text size with collections in Java Swing

我正在尝试使用此代码更改我的 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));

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

据我了解你的问题,你的回答与下面所说的线程第一个答案类似,只需按照此 link -

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

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