2013-09-29 134 views
0

我正試圖做一個程序來獲取用戶從鍵盤輸入的JFrame窗口。所以如果用戶輸入一個單詞,語句類應該看看單詞是否在那裏然後打印出來。Java KeyListener不起作用

因爲它現在我不能讓語句類工作惠特鍵盤類。 我真的不想用這種方式來獲得鍵盤輸入,所以我認爲你會知道更好的方式,將是篦。

問題:修復,以便語句類獲取鍵盤輸入。

這是結類:

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

您需要添加KeyListener到您在使用的JFrame,使其工作的每個組件和

setFocusable(true);爲好。

但是,如果你想添加KeyListenerJFrame,創建自定義KeyEventDispatcher並將其註冊到KeyboardFocusManager,如:

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

(我會使用JPanel和所有組件添加到JPanel而不是JFrame

+0

對我而言,我只使用JPanels。 'JPanel'的'JFrame'唯一容器/包裝器。我知道'setFocusable'適用於'JPanel' –

+0

不知道,請發佈您的答案,生病刪除我的 –

+0

大聲笑,好吧,虐待改變我的答案與您的提示 –