javafx键盘事件快捷键

Him*_*rma 6 javafx keycode

我想在javafx中添加键盘快捷键.

我有场景,想要实现键盘快捷方式

我的代码如下

getApplication().getScene().setOnKeyPressed(new EventHandler<KeyEvent>() {

        public void handle(KeyEvent ke) {
            if (ke.getCode() == KeyCode.ESCAPE) {
                System.out.println("Key Pressed: " + ke.getCode());
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

use*_*691 15

事件从场景传播到聚焦节点(事件捕获),然后返回到场景(事件冒泡).在事件捕获期间触发事件过滤器,而在事件冒泡期间触发onKeyPressed和事件处理程序.某些控件(例如TextField)使用该事件,因此它永远不会返回到场景,即取消事件冒泡并且场景的onKeyPressed不起作用.

要获取所有按键事件,请使用addEventFilter方法:

scene.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
    public void handle(KeyEvent ke) {
        if (ke.getCode() == KeyCode.ESCAPE) {
            System.out.println("Key Pressed: " + ke.getCode());
            ke.consume(); // <-- stops passing the event to next node
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

如果要捕获组合键,请使用KeyCodeCombination类:

scene.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
    final KeyCombination keyComb = new KeyCodeCombination(KeyCode.ESCAPE,
                                                          KeyCombination.CONTROL_DOWN);
    public void handle(KeyEvent ke) {
        if (keyComb.match(ke)) {
            System.out.println("Key Pressed: " + keyComb);
            ke.consume(); // <-- stops passing the event to next node
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

还可以通过设置加速器来向菜单添加快捷方式(参见[2]).

参考


Ita*_*iha 2

我不确定你在做什么getApplication,但只是为了KeyEventHandlerScene作品中展示这一点,这里有一个演示给你。

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class MyApp extends Application {
    public void start(Stage stage) {

        VBox root = new VBox();
        root.setAlignment(Pos.CENTER);
        Label heading = new Label("Press Key");
        Label keyPressed = new Label();
        root.getChildren().addAll(heading, keyPressed);
        Scene scene = new Scene(root, 400, 300);

        scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
            public void handle(KeyEvent ke) {
                keyPressed.setText("Key Pressed: " + ke.getCode());
            }
        });

        stage.setTitle("My JavaFX Application");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
Run Code Online (Sandbox Code Playgroud)