我正在尝试通过按箭头键在Java框架中创建一个可移动对象。 不知怎的,我的动画没有做任何事情,也没有通过System.out.println()显示keyCode(如果我要按错键)。
这是我的代码,我希望有人可以浏览一下,也许可以自己测试一下,找出问题出在哪里?我会非常感激,因为我现在坚持了几个小时:(
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class GUI extends JPanel implements ActionListener, KeyListener{
Timer tm = new Timer(5, this);
int x = 0, y = 0, velX = 0, velY = 0;
public GUI(){
tm.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(x, y, 30, 30);
}
public void actionPerformed(ActionEvent e){
x = x + velX;
y = y + velY;
repaint();
}
public void keyPressed(KeyEvent e){
int c = e.getKeyCode();
if(c == KeyEvent.VK_LEFT){
velX = -1;
velY = 0;
}
else if(c == KeyEvent.VK_UP){
velX = 0;
velY = -1;
}
else if(c == KeyEvent.VK_RIGHT){
velX = 1;
velY = 0;
}
else if(c == KeyEvent.VK_DOWN){
velX = 0;
velY = 1;
}
else System.out.println(e.getKeyChar() + " = " + c);
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public static void main(String[] args){
GUI t = new GUI();
JFrame jf = new JFrame();
jf.setTitle("Animation");
jf.setSize(600,400);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(t);
}
}
答案 0 :(得分:1)
在main
方法中,在致电JPanel
之前将JFrame
添加到setVisible
:
public static void main(String[] args){
GUI t = new GUI();
JFrame jf = new JFrame();
jf.add(t);
jf.setTitle("Animation");
jf.setSize(600,400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}