1

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

4

1 回答 1

0

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

以下代码保持 的宽度RectangleText.

@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();
}
于 2018-06-05T09:36:08.627 回答