从Contextmenu显示Colorpicker

时间:2015-05-24 19:56:52

标签: javafx javafx-8

我想从上下文菜单中显示Colorpicker:

ColorPicker colorssPicker = new ColorPicker();

    final MenuItem resizeItem = new MenuItem("Option 1");
    resizeItem.setOnAction(new EventHandler<ActionEvent>()
    {
        @Override
        public void handle(ActionEvent event)
        {

        }
    });

    final MenuItem resizesItem = new MenuItem();
    resizesItem.setGraphic(colorssPicker);
    resizesItem.setOnAction(new EventHandler<ActionEvent>()
    {
        @Override
        public void handle(ActionEvent event)
        {

        }
    });

    final ContextMenu menu = new ContextMenu();

    menu.getItems().addAll(resizeItem, resizesItem);

    sc.setOnMouseClicked(new EventHandler<MouseEvent>()
    {
        @Override
        public void handle(MouseEvent event)
        {
            if (MouseButton.SECONDARY.equals(event.getButton()))
            {
                menu.show(primaryStage, event.getScreenX(), event.getScreenY());
            }
        }
    });

此代码无法正常工作,当我点击Contextmenu“选择颜色”时,我看不到Colorpicker。实现这个的正确方法是什么?

我得到了这个结果:

enter image description here

1 个答案:

答案 0 :(得分:2)

This snippet will let you show a ColorPicker control embedded into a ContextMenu.

You can style it so it doesn't look like a button, by setting its backgound color.

@Override
public void start(Stage primaryStage) {
    StackPane root = new StackPane();

    final ColorPicker colorssPicker = new ColorPicker();
    colorssPicker.setStyle("-fx-background-color: white;");

    final MenuItem otherItem = new MenuItem(null, new Label("Other item"));

    final MenuItem resizeItem = new MenuItem(null,colorssPicker);
    resizeItem.setOnAction(new EventHandler<ActionEvent>(){
        @Override
        public void handle(ActionEvent event)
        {
            root.setBackground(new Background(new BackgroundFill(colorssPicker.getValue(),null,null)));
        }
    });

    final ContextMenu menu = new ContextMenu(otherItem,resizeItem);

    Scene scene = new Scene(root, 300, 250);
    scene.setOnMouseClicked(new EventHandler<MouseEvent>(){
        @Override
        public void handle(MouseEvent event){
            if (MouseButton.SECONDARY.equals(event.getButton())){
                menu.show(primaryStage, event.getScreenX(), event.getScreenY());
            }
        }
    });

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

ColorPicker