How can I style a JavaFX menu and its items in CSS

2019-01-18 23:13发布

I've got a MenuBar that is setup as follows in FXML:

<MenuBar VBox.vgrow="NEVER">
    <menus>
        <Menu mnemonicParsing="true" text="_File">
            <items>
                <MenuItem mnemonicParsing="true" text="_New Project"/>
                <MenuItem mnemonicParsing="true" text="_Open…"/>
                <MenuItem mnemonicParsing="false" text="Quit"/>
            </items>
        </Menu>
    </menus>
</MenuBar>

This produces a menu as follows:

enter image description here

I've successfully styled the MenuBar and the Menu File with the following CSS:

.menu-bar { /* The menu bar itself */ }
.menu { /* The File menu item */ }
.menu:showing { /* menu when it's being shown (activated) */ }
.menu .label { /* Styles the text on a menu item */ }
.menu:showing .label { /* Styles the text on a menu item when activated */ }

However, I've been unable to style the menu that is displayed.

I've tried treating it as a ContextMenu:

.context-menu {
    -fx-background-color: red;
}

Doesn't do anything (it's not a ContextMenu, so no big surprise here).

I've tried styling menu-item and menu-button:

.menu-button,
.menu-item {
    -fx-background-color: red;
}

This changes the menu (File), but not the menu items or the menu that is displayed.

I've tried selecting a substructure called .items but that doesn't seem to exist.

Questions

  1. How do I select/style the menu (the container that is holding New Project, Open..., Quit)?
  2. How do I select/style each individual MenuItem in the menu?

Clarification

To help clarify which elements I'm looking to style, I've added this image which outlines the components I'm wishing to style:

enter image description here

1条回答
时光不老,我们不散
2楼-- · 2019-01-18 23:49

I think you forgot the -fx-skin property in .context-menu.
Follow the How to style menu button and menu items.

查看更多
登录 后发表回答