所以我想將字符串移向用戶推送的方向,但它不起作用。它與mouselistener一起工作,所以我認爲這是足夠的。我應該把聽衆添加到其他東西嗎?在JFrame上使用KeyListener來移動組件
public class Snake extends JComponent implements KeyListener{
private int x;
private int y;
private String s;
public Snake(String s, int x, int y){
this.s = s;
this.x = x;
this.y = y;
addKeyListener(this);
}
@Override
protected void paintComponent(Graphics g) {
g.drawString(s, x, y);
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
switch(code) {
case KeyEvent.VK_UP:
y-=15;
case KeyEvent.VK_DOWN:
y+=15;
case KeyEvent.VK_RIGHT:
x+=15;
case KeyEvent.VK_LEFT:
x-=15;
}
repaint();
}
@Override
public void keyReleased(KeyEvent e) {
}
}
public class Game {
public static void main(String[] args){
JFrame frame = new JFrame("Up Up And Away!");
JComponent star = new Snake("*", 250, 100);
frame.add(star);
frame.setSize(500, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
避免使用'KeyListener'爲了這個目的,可以使用[鍵綁定(http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html),而不是 – BackSlash 2014-09-29 06:51:29
檢查這個環節可能是對你有幫助。 http://stackoverflow.com/questions/286727/java-keylistener-for-jframe-is-being-unresponsive – Rana 2014-09-29 06:59:44
http://stackoverflow.com/a/26098190/1966247這裏我已經解決了你的問題,你檢查它:),我希望你會得到它有幫助 – Muhammad 2014-09-29 11:02:09