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)
Asked
Active
Viewed 316 times
1
-
Possible duplicate of [Calculate the display width of a string in Java](https://stackoverflow.com/questions/258486/calculate-the-display-width-of-a-string-in-java) – Logan Jun 05 '18 at 09:21
-
2see [this](https://docs.oracle.com/javase/10/docs/api/java/awt/FontMetrics.html#stringWidth(java.lang.String)) – Ashwin K Kumar Jun 05 '18 at 09:22
1 Answers
0
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();
}

fabian
- 80,457
- 12
- 86
- 114
-
"The `Text` node does not need to be attached to a scene for this to work." => does this mean the layout is performed immediately upon initialization (and subsequent changes)? Can it be performed outside of the JavaFX UI thread? – Itai Jun 05 '18 at 11:15