问题描述
我想将Text设置为等宽字体。最后,我选择了GT Pressura Mono Regular Regular。
但是,关于他的事情很奇怪。我发现文本不是等宽的,尽管字母宽度的差异很小。
我以为字体有问题,但是我尝试了其他等宽字体(包括从Windows下载和从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
解决方法
该问题很可能是由于找不到字体而引起的。
在设置文本(或系统支持的某些常用字体)之前,请尝试运行以下调用。然后尝试使用您的字体系列。如果找不到任何字体,则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);