在Java Swing中使用集合调整JLabel文本大小
我正在尝试使用以下代码更改我的JLabel文本大小:在Java Swing中使用集合调整JLabel文本大小,java,swing,text,size,jlabel,Java,Swing,Text,Size,Jlabel,我正在尝试使用以下代码更改我的JLabel文本大小: my_font = my_label.getFont(); my_font = my_font.deriveFont( Collections.singletonMap( TextAttribute.SIZE, TextAttribute.20)); 这一行上有一个编译器警告: TextAttribute.20; 此代码工作正常,并更改了文本权重: font_bold = numero_f
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));
问题:我如何使用相同的代码来更改文本大小?据我所知,您的答案与下面所述的主题类似。首先,请点击此链接-
希望这对您有所帮助,谢谢。非常感谢!我是这个网站的新手,我正在学习。这一评论非常有用。
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));