ContextMenu并以编程方式选择一个项目 [英] ContextMenu and programmatically selecting an item
问题描述
似乎没有用于以编程方式选择" ContextMenu项的API?选择我"的意思是点击向上和向下键(或将鼠标悬停在某个项目上).当显示ContextMenu时,我真的只需要选择第一项.我试图在显示菜单时触发向下的按键事件,但是什么也没发生..也许是我错误地构造了该事件.
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 over an item). I really only need to select the first item, when a ContextMenu is shown. I attempted to fire a down keyevent upon showing the menu, but nothing happened.. perhaps I constructed the event wrongly.
推荐答案
要使其正常工作,我们可以使用一些私有API. ContextMenu
外观(ContextMenuSkin
)使用ContextMenuContent
对象作为包含所有项目的容器.
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.
但是为此,我们可以使用一些查找来找到第一个menu-item
CSS选择器.必须在显示阶段之后执行此操作.
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();
}
});
}
这篇关于ContextMenu并以编程方式选择一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!