【问题标题】:What is the supported method of calculating string width (pixels) in JDK 10JDK 10 中支持的计算字符串宽度(像素)的方法是什么
【发布时间】:2018-06-05 09:20:14
【问题描述】:

我不想使用 AWT。 我正在使用 FontMetrics.computeStringWidth() 但在 JDK 10 中消失了,破坏了我的应用程序。是否有不需要引入新框架的替代方案(我正在使用 javafx)

【问题讨论】:

标签: java javafx fontmetrics


【解决方案1】:

您可以使用Text 并从boundsInLocal 属性中获取大小。 (Text 节点不需要附加到场景即可。)

以下代码保持Rectangle 的宽度与Text 的大小相同。

@Override
public void start(Stage primaryStage) throws Exception {
    Text text = new Text();
    TextField textField = new TextField();
    Rectangle rect = new Rectangle(0, 20);

    textField.textProperty().addListener((o, oldValue, newValue) -> {
        text.setText(newValue);
        rect.setWidth(text.getBoundsInLocal().getWidth());
    });

    Scene scene = new Scene(new VBox(textField, text, rect), 600, 400);
    primaryStage.setScene(scene);
    primaryStage.show();
}

【讨论】:

  • Text 节点不需要附加到场景才能工作。” => 这是否意味着布局在初始化(以及后续更改)时立即执行?可以在 JavaFX UI 线程之外执行吗?
猜你喜欢
  • 1970-01-01
  • 2012-10-12
  • 2011-02-24
  • 1970-01-01
  • 2013-08-22
  • 2011-09-15
  • 1970-01-01
  • 2019-04-08
  • 2010-11-28
相关资源
最近更新 更多