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

最佳答案

您可以使用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();
}

09-10 03:17
查看更多