首页 > 解决方案 > 为什么 JavaFX 中的某些文本边界不一致,我该如何避免?

问题描述

我正在使用Text节点来计算字符串的维度,如此处所述总结为:

new Text("some text").getLayoutBounds();

对于相同的输入字符串,返回的尺寸在不同的执行点并不总是相同的,并且其他一切都相同(字体等)。似乎不一致与退格键与 a 的交互有关TextArea即使此 TextArea 与 Text 节点无关。

这是一个间歇性/非确定性问题,但其他人能够使用以下代码重现它:

public class Test extends Application {
    private Text text = new Text();
    
    public static void main(String... args) {
        launch(args);
    }
    
    public void start(Stage stage) {
        TextArea textArea = new TextArea();
        textArea.textProperty().addListener((observable, oldValue, newValue) -> {
            text.setText(newValue);
            System.out.println(String.format("height=%.1f", text.getLayoutBounds().getHeight()));
        });

        stage.setScene(new Scene(new Group(textArea)));
        stage.show();
    }
}

键入几个“X”字符,我得到(在 Windows 上)height=16.0:. 输入退格键后(但当字符串中仍有几个“X”字符时),我得到height=17.0. 如果我输入更多字符,高度保持不变17.0,然后任意移回 16.0,然后是 17.0,等等。其他用户报告了不同类型的不稳定行为。

是什么导致了这种不一致,我该如何避免呢?

标签: javajavafx

解决方案


推荐阅读