如何在Java中正确使用keyListener [英] How to use keyListener properly in Java

查看:845
本文介绍了如何在Java中正确使用keyListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在Java中使用KeyListener时遇到问题.
我正在尝试编写一个程序,该程序在按下某个键之前一直运行,然后输出该键.
这是编写更详细代码的垫脚石,因此使用一种方法来打印按下的键只是作为一种原型.

I am running into problems trying to use KeyListener in java.
I am trying to write a program that runs until a key is pressed, and then outputs that key.
This is a stepping stone to more elaborate code, so the use of a method to print the key pressed is just being used as a kind of prototype.

这是代码:

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

public class keylistener implements KeyListener{
    public keylistener(){
        addKeyListener(this);
    }

    public void keyPressed(KeyEvent e){
        int key = e.getKeyCode();
        keylistener output = new keylistener();
        output.print(key);
    }

    public void keyReleased(KeyEvent e){}
    public void keyTyped(KeyEvent e){}

    public void print(int key){
        System.out.println(key);
    }

    public static void main(String[] args){
    }
}

程序运行,然后直接结束.
我以前从未使用过KeyListener,也无法弄清楚如何使程序等待按键被按下.

The program runs and then ends directly after.
I have never used KeyListener before, and I cannot figure out how to make the program wait for the key to be pressed.

推荐答案

KeyListener旨在在GUI应用程序中使用,而不是在控制台应用程序中使用,因为KeyListener需要运行GUI组件.通常,在控制台应用程序中,您将使用BufferedReader和InputStreamReader.

The KeyListener is intended to be used in GUI apps, not in console apps as KeyListener requires GUI components to run. Usually in a console app you would use a BufferedReader and InputStreamReader.

这里是一个控制台应用程序,它演示了将while循环与BufferedReader和InputStreamReader一起使用的想法,以使该应用程序运行以等待输入.尽管还有其他方法可以做到这一点.我对此进行了非常明确的介绍,以便您可以理解这一概念.

Here is a console app that demonstrates the idea of using a while loop with the BufferedReader and InputStreamReader to keep the app running waiting for input. Although there are other ways to do this. I made this very explicit so you can grasp the concept.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class StackStuff {

public static void main(String[] args) throws IOException {
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
     boolean runs = true ;
     System.out.println("Press any key to kill this app...");
     while(runs){
          input =br.readLine();
         if (!(input==null)){
             System.out.println(input);
             runs=false;
          }
         }
     System.out.println("I am dead!!");
     System.exit(0); 

}

这篇关于如何在Java中正确使用keyListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆