首页 > 解决方案 > 等宽字体在 Java 中不是等宽字体

问题描述

我想将Text设置为等宽字体。最后,我选择了GT Pressura Mono Regular Regular

但是,他身上的某些东西很奇怪。我发现文本不是等宽的,尽管字母宽度的差异很小。

我认为字体有问题,但我尝试了其他等宽字体(下载和从 Windows 下载),但宽度始终不匹配。问题是什么?我只对文本使用大写字母。

请帮忙。

谢谢

更新

我正在添加一个代码以获得更好的说明。

import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextBoundsType;
import javafx.stage.Stage;

public class MonospacedText extends javafx.application.Application {

    @Override
    public void start(Stage stage) {
        var textA = new Text("A");
        textA.setBoundsType(TextBoundsType.VISUAL);
        textA.setFont(new Font("Consolas", 100));
    
        var textB = new Text("B");
        textB.setBoundsType(TextBoundsType.VISUAL);
        textB.setFont(new Font("Consolas", 100));
    
        var textC = new Text("C");
        textC.setBoundsType(TextBoundsType.VISUAL);
        textC.setFont(new Font("Consolas", 100));
    
        var textD = new Text("D");
        textD.setBoundsType(TextBoundsType.VISUAL);
        textD.setFont(new Font("Consolas", 100));
    
        var textE = new Text("E");
        textE.setBoundsType(TextBoundsType.VISUAL);
        textE.setFont(new Font("Consolas", 100));
    
        var vbox = new VBox(textA, textB, textC, textD, textE);
        vbox.setAlignment(Pos.TOP_LEFT);
        stage.setScene(new Scene(vbox));
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

在此处输入图像描述

在图片中已经可以看出字母的宽度不同。此外,当我添加此代码时,它会打印不同的值。

System.out.println(textA.getLayoutBounds().getWidth());
System.out.println(textB.getLayoutBounds().getWidth());
System.out.println(textC.getLayoutBounds().getWidth());
System.out.println(textD.getLayoutBounds().getWidth());
System.out.println(textE.getLayoutBounds().getWidth());

// 54.00390625
// 41.89453125
// 44.091796875
// 46.09375
// 36.279296875

标签: javajavafxtextfontsmonospace

解决方案


该问题很可能发生,因为它无法找到字体。

请在设置文本(或系统支持的一些常见字体)之前尝试运行以下调用。然后尝试使用您的字体系列。如果没有找到任何字体,Java 就无法找到已安装的字体。

System.out.println(Font.getFontNames("Consolas"));

以下适用于我在 Windows 10 中。

Label title = new Label("Testing");
title.setFont(Font.font("Consolas", FontWeight.THIN, 60));
title.setTextFill(Color.RED);

推荐阅读