我很难使方法setOnKeyPressed与MouseEvent.MOUSE_ENTERED一起使用 . 我的目标是只在鼠标位于舞台上的节点(更精确地形状)上时才运行setOnKeyPressed事件,但即使鼠标不在形状上,也会调用我的setOnKeyPressed方法 . 这是我如何创建形状:
Circle circle= new Figura().createCircle(40, 50, 50, Color.BLACK);
root.getChildren().add(circle);
circle.setCenterX(stage.getWidth()/2);
circle.setCenterY(stage.getHeight()/2);
addMouseScrolling(circle);
addKeyPressed(circle); // this handle the 'KeyPressed' and 'Mouse_Entered' events
circle.requestFocus();
以下是我处理mouseEvent setOnKeyPressed的方法:
public void addKeyPressed(Node node) {
node.addEventFilter(MouseEvent.MOUSE_ENTERED, e -> {
node.setOnKeyPressed(t -> {
if (t.getCode()==KeyCode.R) System.out.println("Key "R" pressed!");
});
});
}
正如我所说的,当鼠标悬停在节点上时,我希望将setOnKeyPressed方法调用为ONLY,现在我总是调用它,不仅仅是鼠标在节点上:我创建圆圈(只是创建它不会使setonkeypressed工作)然后我点击它,从现在开始,当我按“r”时,我已经在控制台“Key”R“按下”上打印 . 我希望我能清楚地解释我的问题 . 提前致谢 .
1 回答
最简单的方法是使用
KeyEvent.KEY_PRESSED
处理程序,并将if (node.isHover) { ... }
添加到您的处理程序:您还可以通过添加和删除键事件处理程序来执行此操作,如下所示:
此版本允许您在鼠标进入节点时自动请求关注节点 . 只需修改鼠标输入的处理程序: