What is the supported method of calculating string width (pixels) in JDK 10

329 Views Asked by At

I don't want to use AWT. I was using FontMetrics.computeStringWidth() but is gone in JDK 10 breaking my app. Is there an alternative that doesn't require bringing a new framework (I'm using javafx)

1

There are 1 best solutions below

1
fabian On

You can use Text and get the size from the boundsInLocal property. (The Text node does not need to be attached to a scene for this to work.)

The following code keeps the width of the Rectangle the same as the size of the 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();
}