[英]JavaFX: handle key combination and mouse event simultaneously
我需要對按鍵+鼠標事件組合做出反應,例如:
Ctrl + Shift + R + left_mousebutton_clicked
但我不知道,只有出現Ctrl + Shift + R組合鍵時,如何處理“ left_mousebutton_clicked”。
像這樣的解決方案
if(MouseEvent.isControlDown())
將無法使用,因為任何種類的字母可能有不同的組合鍵。
有任何想法嗎?
您可以使用容器存儲當前按下的鍵:
private final Set<KeyCode> pressedKeys = new HashSet<>();
您可以通過單擊鼠標將偵聽器附加到要定位的控件的“ Scene
上:
scene.setOnKeyPressed(e -> pressedKeys.add(e.getCode()));
scene.setOnKeyReleased(e -> pressedKeys.remove(e.getCode()));
在這些監聽器維護集合的同時,您可以簡單地在目標Node
上附加一個監聽器:
Label targetLabel = new Label("Target Label");
targetLabel.setOnMouseClicked(e -> {
if (e.getButton() == MouseButton.PRIMARY &&
pressedKeys.contains(KeyCode.R) &&
e.isShortcutDown() &&
e.isShiftDown())
System.out.println("handled!");
});
Application
示例:
public class MouseClickExample extends Application {
private final Set<KeyCode> pressedKeys = new HashSet<>();
public static void main(String[] args) {
launch(args);
}
@Override public void start(Stage stage) {
VBox root = new VBox();
Scene scene = new Scene(root, 450, 250);
scene.setOnKeyPressed(e -> pressedKeys.add(e.getCode()));
scene.setOnKeyReleased(e -> pressedKeys.remove(e.getCode()));
Label targetLabel = new Label("Target Label");
targetLabel.setOnMouseClicked(e -> {
if (e.getButton() == MouseButton.PRIMARY && pressedKeys.contains(KeyCode.R) && e.isShortcutDown() && e.isShiftDown())
System.out.println("handled!");
});
root.getChildren().add(targetLabel);
stage.setScene(scene);
stage.show();
}
}
注意:元鍵也存儲在Set
但本示例未使用它們。 也可以在集合中檢查元鍵,而不是使用鼠標事件上的方法。
ctrl和shift都可以按照您在此處提出的方式來完成。 鼠標左鍵是PrimaryButton
if(mouseEvent.isControlDown() && mouseEvent.isShiftDown && mouseEvent.isPrimaryKeyDown){
// Do your stuff here
}
對於“非特殊”鍵(如r),我認為您需要創建一個全局布爾值-以及一個單獨的keyevent偵聽器。 所以:
boolean rIsDown = false;
scene.setOnKeyPressed(e -> {
if(e.getCode() == KeyCode.R){
System.out.println("r was pressed");
//set your global boolean "rIsDown" to true
}
});
scene.setOnKeyReleased(e -> {
if(e.getCode() == KeyCode.R){
System.out.println("r was released");
//set it rIsDown back to false
}
});
然后將其與其他條件一起使用...
if(mouseEvent.isControlDown() && mouseEvent.isShiftDown && rIsDown && mouseEvent.isPrimaryKeyDown){
// Do your stuff here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.