Java KeyListener不起作用

时间:2013-09-29 14:30:26

标签: java swing jframe keylistener setfocus

我正在尝试使用JFrame窗口执行程序,以便从键盘输入用户。因此,如果用户键入一个单词,语句类应该看到该单词是否在那里,然后打印出来。

现在我无法让语句类在键盘类中工作。 我真的不想用这种方式来获取键盘输入,所以我让你们知道任何更好的方法。

问题:修复以使语句类获得键盘输入。

这是声明类:

public class Statements {

Keyboard input;

public Statements(Keyboard input){
    this.input = input; 
}

public void tick() {

    if(input.up){
        System.out.println("inventory");
    }
}

这是键盘类,如果要使用键盘上的所有字符,这是创建键侦听器的一种不好的方法。但这是我知道的唯一方式。

public class Keyboard implements KeyListener {

private boolean[] keys = new boolean[200];
public boolean up, down, left, right, i;

public void update(){
    up = keys[KeyEvent.VK_UP] || keys[KeyEvent.VK_W];
    down = keys[KeyEvent.VK_DOWN] || keys[KeyEvent.VK_S];
    left = keys[KeyEvent.VK_LEFT] || keys[KeyEvent.VK_A];
    right = keys[KeyEvent.VK_RIGHT] || keys[KeyEvent.VK_D];
    //all the char on the keyboard
    ...
    ...
    i = keys[KeyEvent.VK_I];
}

public void keyPressed(KeyEvent e) {
    keys[e.getKeyCode()] = true;
}

public void keyReleased(KeyEvent e) {
    keys[e.getKeyCode()] = false;
}

public void keyTyped(KeyEvent e) {

}

}

主要课程

private static final long serialVersionUID = 1L;

public static final int WIDTH = 100;
public static final int HEIGHT = WIDTH / 16 * 9;
public static final int SCALE = 3;

private boolean running = false;

private Thread thread;
private JFrame frame;
private Keyboard key;
private Statments stat;

public Main() {
    Dimension size = new Dimension(WIDTH * SCALE, HEIGHT * SCALE);
    setPreferredSize(size);

    frame = new JFrame();
    key = new Keyboard();
    stat = new Statments(key);

    addKeyListener(key);


}

public synchronized void start() {
    running = true;
    thread = new Thread(this, "Display");
    thread.start();
}

public synchronized void stop() {
    running = false;
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public void run() {
    while (running) {
        frame.requestFocus();
        tick();
    }
    stop();
}

public void tick(){
    key.update();
    stat.tick();
}

public static void main(String args[]) {
    Main main = new Main();
    main.frame.setResizable(false);
    main.frame.setTitle("game");
    main.frame.add(main);
    main.frame.pack();
    main.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    main.frame.setLocationRelativeTo(null);
    main.frame.setVisible(true);

    main.start();
}

}

1 个答案:

答案 0 :(得分:1)

您需要将KeyListener添加到您在JFrame中使用的每个组件,以使其正常工作

setFocusable(true);也是。

但是,如果您要将KeyListener添加到JFrame,请创建自定义KeyEventDispatcher并将其注册到KeyboardFocusManager,例如:

KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
kfm.addKeyEventDispatcher(new MyKeyEventDispatcher());

(我会使用JPanel并将所有组件添加到JPanel而不是JFrame