java - 为什么 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,等等。其他用户报告了不同类型的不稳定行为。
- 如果您将 替换为
TextArea
,TextField
问题就会消失(!) Text
节点的初始化位置无关紧要。- 在调试时,我看到
valid
标志false
在所有情况下都在 中LazyBoundsProperty#get
,因此似乎为每个新字符重新计算了边界。 - 我在 JavaFX 11.0.2 上得到与 JavaFX 16 相同的行为。
是什么导致了这种不一致,我该如何避免呢?
解决方案
推荐阅读
- apache-flink - Apache Flink 是否支持具有相同时间戳的多个事件?
- jsonschema - JsonSchema:对二进制数据使用类型/格式
- ag-grid - 如何动态获取单元格的滚动容器?
- android - 前台服务会在打瞌睡模式的非唤醒时间工作吗
- jquery - 在haml中添加内联jquery时出现referenceerror
- c# - 下载后解压 zip 文件时,出现异常,提示该文件正在被另一个进程使用
- php - 在 PHP 中找不到类 ParseClient
- javascript - 如何在另一个对象数组中初始化一个对象数组?
- python - 通过视图提交表单时获取“NOT NULL 约束”。通过 /admin 添加时工作正常
- c# - 为什么这个功能和一个完全相同的格式不起作用是有原因的吗?