JavaFX MenuItem without autohide [closed]

安稳与你 提交于 2019-12-02 16:04:18

问题


I want a MenuItem (more specific a CheckMenuItem) which does not auto hide on click. I know that CustomMenuItem has this functionality, but it should be a CheckMenuItem.


回答1:


Use a CustomMenuItem, setHideOnClick and a CheckBox in the constructor.


Edit:

I just noticed that it's messed up in JavaFX 8u40. The menu item text color is the same as the background color, so you don't see any text.

A quick workaround to this is to set the text style, e. g.

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

Here's a full example:

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);
    }
}


来源:https://stackoverflow.com/questions/29622812/javafx-menuitem-without-autohide

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!