我从java lanterna库终端读取用户输入时遇到问题。在击键时我希望系统在终端上打印某个字符。我使用这段代码:
公共课Snake {
public static void main(String[] args) {
Terminal terminal = TerminalFacade.createTerminal(System.in, System.out, Charset.forName("UTF8"));
terminal.enterPrivateMode();
Key key =terminal.readInput();
if (key.getKind() == Key.Kind.Tab)
{
terminal.moveCursor(100, 100);
terminal.putCharacter('D');
}
}
}
不幸的是,我只打开了终端 - 我无法做任何输入。有人知道为什么会这样吗?
答案 0 :(得分:2)
根据给定的代码,您似乎只在主方法执行完毕之前运行了一次if语句。
尝试实现while循环以连续搜索输入:
public static void main(String[] args) {
Terminal terminal = TerminalFacade.createTerminal(System.in, System.out, Charset.forName("UTF8"));
terminal.enterPrivateMode();
// I would recommend changing "true" to a boolean variable that you can flip with a key press.
// For example, the "esc" key to exit the while loop and close the program
Key key;
while(true){
// Read input
key = terminal.readInput();
// Check the input for the "tab" key
if (key.getKind() == Key.Kind.Tab){
terminal.moveCursor(100, 100);
terminal.putCharacter('D');
}
}
terminal.exitPrivateMode();
}