没有自动隐藏的JavaFX MenuItem

JavaFX MenuItem without autohide

我想要一个在点击时不会自动隐藏的 MenuItem(更具体地说是 CheckMenuItem)。我知道 CustomMenuItem 有这个功能,但它应该是一个 CheckMenuItem。

在构造函数中使用 CustomMenuItem, setHideOnClick 和 CheckBox。


编辑:

我刚刚注意到它在 JavaFX 8u40 中搞砸了。菜单项文本颜色与背景颜色相同,因此您看不到任何文本。

一个快速的解决方法是设置文本样式,例如。 g.

cb.setStyle("-fx-text-fill: -fx-text-base-color");

这是一个完整的例子:

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {

            VBox root = new VBox();

             MenuBar menuBar = new MenuBar();

            final Menu menu = new Menu( "Items");

            for( int i=0; i < 10; i++) {

                CheckBox cb = new CheckBox( "Item " + i);

                // workaround: the color of the labels is wrong (white text on white background), we have to set it explicitly
                cb.setStyle("-fx-text-fill: -fx-text-base-color");

                CustomMenuItem cmi = new CustomMenuItem( cb);
                cmi.setHideOnClick(false);

                menu.getItems().add( cmi);

            }

            menu.getItems().add( new MenuItem( "This one doesn't stay open"));

            menuBar.getMenus().add( menu);


            root.getChildren().add( menuBar);

            Scene scene = new Scene(root,400,400);

            primaryStage.setScene(scene);
            primaryStage.show();

        } catch(Exception e) {
            e.printStackTrace();
        }


    }

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