JavaFX Button with multiple text lines

2019-02-27 02:52发布

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:

Button with multiple lines

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

6条回答
相关推荐>>
2楼-- · 2019-02-27 03:21

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

enter image description here

The result is:

enter image description here

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

查看更多
狗以群分
3楼-- · 2019-02-27 03:28

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();
}
查看更多
放我归山
4楼-- · 2019-02-27 03:32

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.

查看更多
聊天终结者
5楼-- · 2019-02-27 03:39
Label label= new Label("your long text here");
label.setStyle("-fx-max-width : 180px);
label.setWrapText(true);
查看更多
Root(大扎)
6楼-- · 2019-02-27 03:46

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.

查看更多
对你真心纯属浪费
7楼-- · 2019-02-27 03:47

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

enter image description here"

查看更多
登录 后发表回答