我有一個JFrame,它在運行時添加了一個keyListener,但是當Frame加載時,會有一個短暫的時間來接收輸入,然後它只停止接收輸入,這裏是Keyboard.java
代碼:Java JFrame沒有收到輸入
package uk.connorwright.rain.input;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Keyboard implements KeyListener {
private boolean[] keys = new boolean[120];
public boolean up, down, left, right;
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];
}
public void keyPressed(KeyEvent e) {
keys[e.getKeyCode()] = true;
}
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode()] = false;
}
public void keyTyped(KeyEvent e) {
}
}
這是Game.java
其中涉及鍵盤輸入代碼:
private Keyboard key;
...
key = new Keyboard();
frame.addKeyListener(key);
....
公共無效更新(){
key.update();
if (key.up) {
y--;
}
if (key.down) {
y++;
}
if (key.left) {
x--;
}
if (key.right) {
x++;
}
}
...
public static void main(String[] args) {
Game game = new Game();
我寧願讓我的代碼工作,然後進行轉換,但在我啓動它的時候,它得到輸入,直到我點擊,然後它停止接收輸入 –
@BasicsCoding如果你想獲得你的代碼工作,然後使用Key Bindings API。正如我所說,如果聽衆註冊的組件是可以聚焦和有焦點的,組件只會引發關鍵的棋盤事件。 – MadProgrammer