菜单大小相同的父级SplitMenuButton javaFX

时间:2016-06-23 05:31:17

标签: java javafx menu

我正在使用JavaFX whit FXML,我想制作一个带有调整大小属性和受限制增长的顶级菜单我在GridePane中使用SplitMenuButtons它工作得很好但是当我添加它看起来像这样的菜单时我有问题

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

菜单噘起很小的

我的想法是将一个侦听器放在SplitMenuButton的widthProperty中,然后设置menu.prefWidth但菜单没有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

对不起,这张坏照片是我手头唯一的东西

所以我如何制作我正在寻找的?,更改4个顶级菜单的节点类型?,CSS(但我认为CSS中的更改是永久性的,如果父更改大小但不确定我不确定)?,其他选择?

1 个答案:

答案 0 :(得分:1)

您可以尝试使用MenuItem的{​​{3}}将Label所需的文字作为图形添加到第一级MenuMenuItem秒。然后,您可以将Label的{​​{3}}绑定到SplitMenuButton的{​​{3}}。

示例

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使其大小相同:您可以查看graphicPropertyprefWidthProperty

还有一个肮脏的解决方案:对于下面的图片,我已将label.prefWidthProperty().bind(menuButton.widthProperty());修改为label.prefWidthProperty().bind(menuButton.widthProperty().subtract(32));

widthProperty