Олег Вялкин Олег Вялкин - 21 days ago 10
Java Question

JavaFx - Wrap content text in alert dialg

How to set wraptext option in an alert dialog box? I tried to do this:

Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.getButtonTypes().set(0, ButtonType.NO);
alert.getButtonTypes().set(1, ButtonType.YES);
alert.getDialogPane().getStylesheets().add("/styles/style.css");
alert.setGraphic(new ImageView(getIcon(icon)));
Label lb = (Label) alert.getDialogPane().getChildren().get(1);
lb.setWrapText(true); //Attempt to set wrapText option
alert.setTitle(title);
alert.setHeaderText(header);
alert.setContentText(content);


But it does not work.

Answer

Create a new label instead, and set it as the content for the DialogPane:

Label label = new Label("Label with\nText that should be wrapped.");
label.setWrapText(true);
alert.getDialogPane().setContent(lb);

Remember that WrapText only wraps on line ending chars (\n), not automatically.

If you want to wrap automatically, use a Text element instead and set the WrappingWidth property:

Text text = new Text("Very long text that should be wrapped in the dialog");
text.setWrappingWidth(100);
alert.getDialogPane().setContent(text);