如何在 Java 中为 Swing 组件设置字体粗细

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25054203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 07:14:32  来源:igfitidea点击:

how to set font weight in Java for Swing components

javaswingfontsfont-size

提问by CRM

I want to set different font weightsfor components on my JFrame dialog. How do I do this?

我想为JFrame 对话框中的组件设置不同的字体粗细。我该怎么做呢?

In the below Java statement

在下面的 Java 语句中

setFont(new Font("Dialog", Font.BOLD, 12));

when I use Font.BOLD it is too bold and when I use Font.Plain it is too plain. I want something in-between.

当我使用 Font.BOLD 时它太粗了,当我使用 Font.Plain 时它太简单了。我想要介于两者之间的东西。

回答by VGR

welle is partially correct. You can use TextAttributesto obtain a font:

Welle 是部分正确的。您可以使用TextAttributes来获取字体:

Map<TextAttribute, Object> attributes = new HashMap<>();

attributes.put(TextAttribute.FAMILY, Font.DIALOG);
attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD);
attributes.put(TextAttribute.SIZE, 12);

label.setFont(Font.getFont(attributes));

A better approach is to derive your font from the font installed on the Swing component by the look-and-feel:

更好的方法是通过外观从 Swing 组件上安装的字体派生您的字体:

Font font = label.getFont();

font = font.deriveFont(
    Collections.singletonMap(
        TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD));

label.setFont(font);

That will preserve the font's family and size, which users may have set in their desktop preferences for readability reasons.

这将保留字体的系列和大小,用户可能出于可读性原因在其桌面首选项中设置了这些。

回答by csWael

maybe i wrong but i think class Font has only Bold ,plain but you can change after that in number

也许我错了,但我认为班级字体只有粗体,普通但你可以在数字之后改变

setFont(new Font("Dialog", Font.BOLD, 12));

setFont(new Font("Dialog", Font.plain, 27));

but in class java.awt.font.TextAttribute

但在课堂上 java.awt.font.TextAttribute

you have WEIGHT_BOLD and WEIGHT_SEMIBOLD ...

你有 WEIGHT_BOLD 和 WEIGHT_SEMIBOLD ...