带有多行文本的JavaFX按钮

7
我需要在我的屏幕上创建一个工具栏,里面有多个按钮,每个按钮中还要有多行文本。例如: Button with multiple lines 我查看了互联网和StackOverflow,但是找不到如何在JavaFX中实现此功能的任何内容。我正在使用JavaFX 8。
请问有人可以帮助我吗?谢谢
6个回答

9

同时,您也可以使用 wrapTextProperty。但是您需要将工具栏高度设置为大于预期按钮高度。

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

或者如果您想要确定行应该被换行的位置,可以采用以下方式:

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

最后一种方法可以在不改变工具栏高度的情况下运行。


3
在按钮文本属性中选择“切换到多行模式”。

enter image description here"


1
好的建议 :) 谢谢! - Zeta.Investigator
如果您是动态生成按钮,则在代码中使用button.setWrapText(true)。 - Pintang

3
我解决了这个问题,将一个VBox包含在我的按钮内部,然后将多个标签包含在VBox内。就像这样: enter image description here 结果是: enter image description here 如果有更优雅的方法可以得到相同的结果,请告诉我。谢谢。

当我这样做时,VBox的toString方法被调用。 - James Robinson

1

根据Sobolev的回应,您可以执行以下操作:

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

这将创建三行文本,并将它们居中对齐在您的按钮上。

0
我的解决方案与原帖中的解决方案基本相同,但是我使用的是Text而不是Label,因此更加灵活,可以根据按钮大小的变化使用所需的行数。如果需要,还可以设置换行宽度以定义宽度约束。
@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();
}

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接