【问题标题】:Check if a key is pressed in console检查是否在控制台中按下了某个键
【发布时间】:2020-03-22 16:33:15
【问题描述】:

我想通过某种方法或事件处理程序检查用户是否按下了 CLI 应用程序中的某个键。

类似的东西:

if(isWPressed)
    System.out.println("'W' is pressed");
if(isAPressed)
    System.out.println("'A' is pressed");

我试过这个答案: How do I check if the user is pressing a key?

但它不起作用,查看导入时我注意到它使用 awt,因此它在没有窗口可言的 CLI 中没有用。我也不能为此使用Scanner(如此处建议的那样:Detect a key press in console),好像用户会按下多个按钮 - 比如w 和a 我需要知道它们都被按下了。

【问题讨论】:

  • 你认为这个库有帮助吗? github.com/jline/jline3
  • 未来可能会有用,但对于这个问题 - 我已经浏览了它的 javadoc,它并没有包含实现我想要的方法。

标签: java keyboard command-line-interface


【解决方案1】:

你需要使用keylistener,它允许获取密钥

Example 

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication7;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 *
 * @author wilso
 */
public class List implements KeyListener {

    @Override
    public void keyTyped(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void keyPressed(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void keyReleased(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}

如果你不想使用awt,那么你可以使用scanner 或Event

@Override
public void nativeKeyPressed(NativeKeyEvent e) {
    String temp = NativeKeyEvent.getKeyText(e.getKeyCode());
    if (validHotKeys.contains(temp)) {
        if (!pressedHotKeys.contains(temp)) {
            pressedHotKeys.add(temp);
            System.out.println(pressedHotKeys.toString());
        }
    }
    if (validAlphaKeys.contains(temp)) {
        if (!pressedAlphaKeys.contains(temp)) {
            pressedAlphaKeys.add(temp);
            System.out.println(pressedAlphaKeys.toString());
        }
    }
}

【讨论】:

  • 他明确表示他不想在他的问题中使用 awt
  • 不是我不想用awt——我不能用awt 至于第二种方案——sign——你需要在上面扩展。通过谷歌搜索,我假设它是 JNativeHook 库的形式,据我所见,它的文档记录很差,并且没有显示如何在控制台中使用 NativeKeyListener
猜你喜欢
  • 1970-01-01
  • 2011-09-22
  • 2014-10-12
  • 1970-01-01
  • 1970-01-01
  • 2017-05-26
  • 2018-05-02
  • 1970-01-01
相关资源
最近更新 更多