You can use the computeTextWidth method in com.sun.javafx.scene.control.skin.Utils . this method is used in the javafx.scene.control.Label class to calculate the minimum width for shortcut content.
I solved my problem as below:
field.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> ob, String o, String n) {
I added a listener to textProperty , and every time I change the text, I change the prefWidth text field.
Note: if Utils.computeTextWidth() not publicly available , I copied the source code to a new class ( TextUtils ).
Here is the complete source code:
package me.jone30rw.fxcontrol; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.scene.text.TextBoundsType; public class TextUtils { static final Text helper; static final double DEFAULT_WRAPPING_WIDTH; static final double DEFAULT_LINE_SPACING; static final String DEFAULT_TEXT; static final TextBoundsType DEFAULT_BOUNDS_TYPE; static { helper = new Text(); DEFAULT_WRAPPING_WIDTH = helper.getWrappingWidth(); DEFAULT_LINE_SPACING = helper.getLineSpacing(); DEFAULT_TEXT = helper.getText(); DEFAULT_BOUNDS_TYPE = helper.getBoundsType(); } public static double computeTextWidth(Font font, String text, double help0) {
source share