与父级相同大小的菜单 SplitMenuButton JavaFX

3
我正在使用JavaFX和FXML开发,希望创建一个具有调整大小属性和受限增长的顶部菜单。为此,我在GridPane中使用了SplitMenuButton,它工作得很好,但是添加菜单时会出现问题,效果如下:

https://postimg.org/image/566jrsvpj/

菜单弹出非常小

我的想法是在SplitMenuButton的widthProperty中放置一个监听器,然后设置menu.prefWidth,但menu没有setPrefWidth或prefWidth方法

所以我绕过它,编写了以下代码添加了带填充的标签,但它看起来很丑陋,而且由于菜单文本的原因,我不知道如何获得正确的大小,也不知道如何计算菜单中文本的大小,这就是我得到的结果

https://s31.postimg.org/96o9nxch7/image.png

它看起来非常丑陋,而且行为随机。我的代码如下:

 SplitMenuButton.widthProperty().addListener((e,n,v)->{
        Label lal = new Label(">");
        Insets inces = new Insets(0,0,0,n.intValue());
        lal.setPadding(inces);
        Menu.setGraphic(lal);
    });

我正在寻找一种方法使菜单和菜单项的大小相同,我所期望的结果是像这样的东西。

https://s32.postimg.org/z6zel4tbp/image.png

抱歉照片质量不佳,这是我手边唯一的东西。
那么我该如何制作我想要的内容呢?更改四个顶部菜单节点的类型?使用 CSS(但我认为 CSS 的更改是永久性的,并且不会重新计算父元素大小,但我不确定)?还有其他选项吗?
1个回答

1
你可以尝试使用MenuItem图形属性,将所需文本的Label作为一级MenuMenuItem上的图形。然后,您可以将Label首选宽度属性绑定到SplitMenuButton宽度属性示例
public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {
            BorderPane root = new BorderPane();
            Scene scene = new Scene(root,400,400);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());


            SplitMenuButton splitMenuButton = new SplitMenuButton();
            splitMenuButton.setPrefWidth(400);

            MenuItem menuItem = new MenuItem();
            prepareMenuItem(menuItem, "I am a MenuItem", splitMenuButton);
            Menu menu = new Menu();
            prepareMenuItem(menu, "I am a Menu", splitMenuButton);
            MenuItem subMenuItem = new MenuItem("I am not resized!");
            menu.getItems().add(subMenuItem);

            splitMenuButton.getItems().addAll(menu, menuItem);

            root.setCenter(splitMenuButton);

            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    private void prepareMenuItem(MenuItem menuItem, String text, MenuButton menuButton){
        Label label = new Label();
        label.prefWidthProperty().bind(menuButton.widthProperty());
        label.setText(text);
        label.setTextAlignment(TextAlignment.RIGHT);
        menuItem.setGraphic(label);
    }

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

然而,结果不会完美,因为下拉菜单中的MenuItem会稍微变宽(因为内部填充),但您可以微调CSS样式类menu-item,使其大小绝对相同:您可以查看modena.cssJavafX CSS Reference Guide
还有一个简单的解决方案:对于以下图片,我已将label.prefWidthProperty().bind(menuButton.widthProperty());修改为label.prefWidthProperty().bind(menuButton.widthProperty().subtract(32));

enter image description here


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