bluevoxel
bluevoxel

Reputation: 5358

How to adjust Label's width to fit its content?

How one can adjust minimum width of the JavaFX 8 (8_45) Label control item according to its content? To this very moment I had to adjust size of my GUI components manually, in order to be sure, that their content will be visible no matter what will happen with the size of its parent (eg. HBox, Scene, Stage or whatever), ie.:

Label label = new Label("Foo foo foo");
label.setMinWidth(someMinValue);

Is there a way to make Label or any other JavaFX control item to "listen" its content and adjust its width to it automatically? Thank you in advance.

Upvotes: 9

Views: 17107

Answers (2)

Zyxl
Zyxl

Reputation: 124

Here's a solution where you can also set a min and max width based on the size of the unclipped content.

For example, if you want to limit how much the label can get clipped and how long the label can be, but otherwise have the label width be the exact length necessary to show the full content. Here I show at least half of the unclipped width and at least 50px, but max 200px:

label.minWidthProperty().bind(Bindings.createDoubleBinding(
        () -> Math.max(label.prefWidth(-1) / 2, 50), // Show at least half of content and at least 50px
        label.textProperty(), label.graphicProperty(), label.prefWidthProperty(), label.layoutBoundsProperty()));
label.maxWidthProperty().bind(Bindings.createDoubleBinding(
        () -> Math.min(label.prefWidth(-1), 200), // Show content up to 200px
        label.textProperty(), label.graphicProperty(), label.prefWidthProperty(), label.layoutBoundsProperty()));

This is robust to changes in the label text or graphic. If you're going to change other things affecting the content size after the label is rendered then you may need to add some other observables to the list of dependencies, e.g. label.graphicTextGapProperty().

Upvotes: 0

Steven Van Impe
Steven Van Impe

Reputation: 1163

If you want to make sure your label stays big enough for the text it holds, you probably want to set its minimum size to track its preferred size:

label.setMinWidth(Region.USE_PREF_SIZE);

Upvotes: 17

Related Questions