首页 > 解决方案 > 如何根据 JavaFX 中的文本调整按钮的大小?

问题描述

这可能是一个微不足道的问题,但到目前为止我无法找到解决方案。
如果您创建一个带有较长单词作为文本的按钮,让我们说“Überspringen”(跳过的德语单词),JavaFx 会自动将文本截断为“Übersprin”+EllipsisString。
Button skipButton = new Button("\u00dcberspringen");
在此处输入图像描述

有没有简单的解决方案来避免截断?我只能硬编码一个新的大小,但在 Swing 中,按钮大小是自动调整的。

我已经尝试过setWrapText(true)了,但是没有用,我想是因为没有空格。

编辑

这个最小的、可重现的示例显示了我的问题:
public class ButtonTest extends Application
{

    public static void main(String[] args)
    {
       Application.launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception
    {
       Scene scene = new Scene(getBottomPanel(),600,50);
       primaryStage.setScene(scene);
       primaryStage.show();
    }

    private AnchorPane getBottomPanel()
    {
       HBox infraBox = new HBox(5);
       infraBox.setAlignment(Pos.CENTER);
       infraBox.getChildren().add(new Label("Input (manuell):"));
       infraBox.getChildren().add(new TextField());

       Button shortButton = new Button("OK");
       Button longButton = new Button("\u00dcberspringen");
       ButtonBar buttonBar = new ButtonBar();
       buttonBar.getButtons().addAll(shortButton, longButton);

       AnchorPane bottomPanel = new AnchorPane(infraBox, buttonBar);
       bottomPanel.setPadding(new Insets(5));
       AnchorPane.setLeftAnchor(infraBox, 0.0);
       AnchorPane.setRightAnchor(buttonBar, 5.0);
       return bottomPanel;
    }
}

标签: javabuttonjavafxresize

解决方案


通常按钮会调整大小,以便按钮的标签完全可见:

“例如,Button 对象的计算大小由文本长度和用于标签的字体大小以及任何图像的大小决定。通常,计算出的大小对于控件和标签完全可见。” (https://docs.oracle.com/javase/8/javafx/layout-tutorial/size_align.htm)。

但是,当您将按钮存储在具有最大宽度和高度的容器(例如VBoxHBox)中时,例如,按钮将被挤压到该容器中,即标签被截断:

“默认情况下,按钮只会增长到它们的首选大小。但是,如果没有覆盖最小宽度,按钮会缩小到标签显示为三个点 (...) 的位置。”。

我链接的文章描述了您的问题:

“为了防止按钮变得小于其首选宽度,请将其最小宽度设置为其首选宽度”,在“将节点保持在首选大小”部分中。

如果您没有手动设置按钮的首选大小,则计算的大小将自动用于其首选大小:

“默认情况下,UI 控件根据控件的内容计算其首选大小的默认值”

您的代码示例不会产生所描述的问题(对我来说):

示例应用程序的屏幕截图

(对不起,我想评论你的帖子,但我的声誉太低了)


推荐阅读