JavaFX Button with multiple text lines

2019-02-27 02:42发布

问题:

I need to create a toolbar in my screen that will have multiple buttons, and each button must have multiple lines of Text. For example:

I looked over the internet and StackOverflow but I couldn't find anything showing how to do this in JavaFX. I'm using JavaFX 8.

Someone could help me, please?

Tks

回答1:

Also you can use the wrapTextProperty. But you have to set toolbar height greater than expected button height.

Button btn = new Button();
btn.wrapTextProperty().setValue(true);
// or btn.setWrapText(true);
btn.setText("Some looooooooooooong text");

Or if you want to determine exactly where the line should be wrapped, you can go this way:

Button btn = new Button();
btn.setText("Line1\n Line2\n Line3");

Last way will work without changing toolbar height.



回答2:

I resolved this problem including a VBox inside my button, and then including several Labels inside the VBox. Like this:

The result is:

If there is a more elegant way to have the same result, please, let me know. Thank you.



回答3:

In the button text property select "switch to multi-line mode

"



回答4:

My solution is pretty much the same as the one given by the OP, but instead of Label uses Text so it's more flexible to changes in the size of the button, as it will use as many lines as needed. If required, also one can set a wrapping width, to define a width constraint.

@Override
public void start(Stage primaryStage) {
    Button btn = new Button();
    ImageView imageView = new ImageView(new Image(getClass().getResource(<image>).toExternalForm()));
    Text text=new Text("Some long text that may be line wrapped");
    text.setWrappingWidth(100);
    VBox vBox = new VBox(5, imageView,text);
    vBox.setAlignment(Pos.CENTER);
    btn.setGraphic(vBox);
    btn.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);

    Scene scene = new Scene(new StackPane(btn), 300, 250);

    primaryStage.setScene(scene);
    primaryStage.show();
}


回答5:

Label label= new Label("your long text here");
label.setStyle("-fx-max-width : 180px);
label.setWrapText(true);


回答6:

From sobolev's response, you can do:

Button btn = new Button();
btn.setText("Line1\n Line2\n Line3");
button.textAlignmentProperty().set(TextAlignment.CENTER);

This will create 3 lines of text and allign them in the center of your button.