ContextMenu and programmatically selecting an item

前端 未结 1 1880
轮回少年
轮回少年 2021-01-16 19:28

There does not seem to be API for programmatically \"selecting\" ContextMenu items? By selecting I mean the equivalent of tapping up and down keys (or hovering the mouse ove

相关标签:
1条回答
  • 2021-01-16 19:44

    To get this working, we could use some private API. ContextMenu skin (ContextMenuSkin) uses a ContextMenuContent object, as a container with all the items.

    We just need to request the focus for the first of these items.

    But for this we could just use some lookups to find the first menu-item CSS selector. This has to be done after the stage has been shown.

    This example will show a context menu with focus on the first item:

    @Override
    public void start(Stage primaryStage) {
    
        MenuItem cmItem1 = new MenuItem("Item 1");
        cmItem1.setOnAction(e->System.out.println("Item 1"));
        MenuItem cmItem2 = new MenuItem("Item 2");
        cmItem2.setOnAction(e->System.out.println("Item 2"));
    
        final ContextMenu cm = new ContextMenu(cmItem1,cmItem2);
    
        Scene scene = new Scene(new StackPane(), 300, 250);
    
        primaryStage.setScene(scene);
        primaryStage.show();
    
        scene.setOnMouseClicked(t -> {
            if(t.getButton()==MouseButton.SECONDARY){
                cm.show(scene.getWindow(),t.getScreenX(),t.getScreenY());
    
                // Request focus on first item
                cm.getSkin().getNode().lookup(".menu-item").requestFocus();
            }
        });        
    }
    
    0 讨论(0)
提交回复
热议问题