如何根据箭头键的输入移动图形?

时间:2015-04-16 09:29:04

标签: java swing jframe graphics2d japplet

我正在制作一个图形,其中圆圈应该用箭头键移动,但我检查了我的代码但找不到问题。小程序正在工作并初始化,但是当我按下箭头键时圆圈没有移动。你能帮帮我吗?

public class second extends JPanel implements ActionListener, KeyListener{

Timer t = new Timer(5,this);
double x = 0, y = 0, velx = 0, vely = 0;

public second() {
    t.start();
    addKeyListener(this);
    setFocusable(true);
    setFocusTraversalKeysEnabled(false);
}

public void paintComponent(Graphics g){
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.fill(new Ellipse2D.Double(x,y,40, 40));    
}

public void actionPerformed(ActionEvent e){
    repaint();
    x += velx;
    y += vely;
}

public void up(){
    vely = -1.5;
    velx = 0;        
}

public void down(){
    vely = 1.5;
    vely = 0;
}

public void left(){
    velx = -1.5;
    vely = 0;
}

public void right(){
    velx = 1.5;
    vely = 0;
}

public void keyPressed(KeyEvent e){
    int code = e.getKeyCode();
    if (code == KeyEvent.VK_UP){
        up();
    }
    if (code == KeyEvent.VK_DOWN){
        down();
    }
    if (code == KeyEvent.VK_LEFT){
        left();
    }
    if (code == KeyEvent.VK_RIGHT){
        right();
    }
    repaint();
}

public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e) {}

}

0 个答案:

没有答案