java 如何字体
设置字体样式
在Java中,可以通过java.awt.Font类来设置字体样式。以下是一个基本示例:
Font font = new Font("Serif", Font.BOLD, 16);
- 第一个参数指定字体名称,如"Arial"、"Times New Roman"等
- 第二个参数指定字体样式,可以是
Font.PLAIN、Font.BOLD或Font.ITALIC - 第三个参数指定字体大小
在Swing组件中使用字体
对于Swing组件,可以通过setFont()方法应用字体:

JLabel label = new JLabel("Hello World");
label.setFont(new Font("Arial", Font.BOLD, 24));
获取系统可用字体
要获取系统上所有可用字体:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames = ge.getAvailableFontFamilyNames();
for (String name : fontNames) {
System.out.println(name);
}
在JavaFX中使用字体
对于JavaFX应用,使用javafx.scene.text.Font类:

Font font = Font.font("Verdana", FontWeight.BOLD, 20);
Label label = new Label("JavaFX Text");
label.setFont(font);
加载外部字体文件
要加载外部TTF或OTF字体文件:
try {
Font customFont = Font.createFont(Font.TRUETYPE_FONT, new File("path/to/font.ttf"));
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(customFont);
} catch (IOException | FontFormatException e) {
e.printStackTrace();
}
测量文本尺寸
获取文本在特定字体下的宽度和高度:
FontMetrics metrics = component.getFontMetrics(font);
int width = metrics.stringWidth("Sample Text");
int height = metrics.getHeight();






