简体   繁体   English

JavaFX键监听器为多键按下实现?

[英]JavaFX key listener for multiple keys pressed implementation?

I would like to create an event handler that listens for multiple key combinations such as holding Ctrl and C at the same time. 我想创建一个事件处理程序来侦听多个键组合,例如同时按住CtrlC.

Why doesn't something like if((... == Control) && (... == C)) work? 为什么if((... == Control) && (... == C))不起作用?

Here is the code I trying to work with: 这是我尝试使用的代码:

textField.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
    public void handle(KeyEvent event) {
        if ((event.getCode() == KeyCode.CONTROL) && (event.getCode() == KeyCode.C)) {
            System.out.println("Control pressed");
        } 
    };
});

You can try this solution, it worked for me! 你可以尝试这个解决方案,它对我有用!

final KeyCombination keyCombinationShiftC = new KeyCodeCombination(
KeyCode.C, KeyCombination.CONTROL_DOWN);

textField.setOnKeyPressed(new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent event) {
        if (keyCombinationShiftC.match(event)) {
            logger.info("CTRL + C Pressed");
        }
    }
});

One way to tackle this problem is to create a KeyCombination object and set some of its properties to what you see below. 解决此问题的一种方法是创建KeyCombination对象并将其某些属性设置为您在下面看到的内容。

Try the following: 请尝试以下方法:

textfield.getScene().getAccelerators().put(new KeyCodeCombination(
    KeyCode.C, KeyCombination.CONTROL_ANY), new Runnable() {
    @Override public void run() {
        //Insert conditions here
        textfield.requestFocus();
    }
});

A bit more concise (avoids new KeyCombination() ): 更简洁(避免new KeyCombination() ):

public void handle(KeyEvent event) {
    if (event.isControlDown() && (event.getCode() == KeyCode.C)) {
        System.out.println("Control+C pressed");
    } 
};

There are methods of the type KeyEvent.isXXXDown() for the other modifier keys as well. KeyEvent.isXXXDown()类型的方法也适用于其他修饰键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM