Reputation: 23
I am new developer and I try to make a program. in my program there is a list of messages (listMessages
) and each message in it is a MessageItemController
which I created (a custom control) with a VBox
in it that contains a label and some other things. Sudo code of that VBox
in MessageItemController
:
<VBox fx:id="VBoxContent" GridPane.columnIndex="1" GridPane.rowIndex="1" GridPane.vgrow="ALWAYS">
<children>
<Label fx:id="lblMessage" text="message" textOverrun="CLIP" wrapText="true">
<padding>
<Insets left="10.0" />
</padding>
</Label>
...
</children>
</VBox>
I want to VBoxContent
has a maximum width. before, I set a MaxWidth
for my VBoxContent
to for example 300px. (I do this in scenebuilder and my fxml file not with code). It's work perfectly. all my message which I add to my listMessages
work.
Now I changed my idea and I want MessageItemController
to has maxWidth but 0.5 percent of its parent (I mean listMessages
which I add this messages to them). so I remove maxWidth
from my fxml file and add this code in my controller:
listMessages.widthProperty().addListener((observable, oldValue, newValue) -> {
if (observableListMessages != null)
observableListMessages.forEach(x -> {
x.VBoxContent.setMaxWidth(0.5 * newValue.doubleValue());
});
});
but maybe wrapText
of label doesn't work if I set MaxWidth
(or even PrefWidth
) for my VBox
from code (not fxml).
Is it possible to help my problem? If you can say how can I make text wrap or if it is not possible and it is problem of javafx so if there is any idea to achieve my purpose, please say it.
I'm sorry for bad English. Thanks.
Upvotes: 2
Views: 5220
Reputation: 1
What worked for me was:
label.setMinHeight(Region.USE_PREF_SIZE);
Upvotes: 0
Reputation: 73
Wrap your text in a thing called TextFlow
in your FXML. It will save you so much headaches.
Upvotes: 2
Reputation: 10253
You need to set the prefWidth
for the Label
itself.
Here is a short demo application:
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
VBox root = new VBox(5);
root.setPadding(new Insets(10));
Label label = new Label("This is some long text that should be wrapped.");
label.setWrapText(true);
label.setPrefWidth(100);
root.getChildren().add(label);
primaryStage.setWidth(200);
primaryStage.setHeight(200);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
Until you set the preferred width for your Label
, it doesn't really know where you want to start wrapping.
If you want the label to wrap with the size of your VBox
, you could bind the PrefWidthProperty
of your Label
to the WidthProperty
of the VBox
instead:
label.prefWidthProperty().bind(root.widthProperty());
Doing this will allow your text to fill the width of its container, but wrap if it's too long.
Upvotes: 4