麻烦在Java中移动对象

时间:2016-04-06 18:17:11

标签: java swing animation actionlistener keylistener

当我点击箭头按钮时,我试图创建一个移动的球。但是当我点击箭头按钮时,球没有响应。当我点击箭头按钮时,我试图创建一个移动的球。但是当我点击箭头按钮时,球没有响应。这是我的代码:

package ball.main;

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.JPanel;
import javax.swing.Timer;

public class Ball extends JPanel implements ActionListener, KeyListener {

    Timer t = new Timer(5, this);

    int x = 0;
    int y = 0;
    int velX;
    int velY;

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.GREEN);
        g.fillOval(x, y, 20, 20);
        t.start();
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        if (x < 0) {
            x = 0;
        }
        if (x > 580) {
            x = 580;
        }
        if (y < 0) {
            y = 0;
        }
        if (y > 580) {
            y = 580;
        }

        x += velX;
        x += velY;
        repaint();

    }

    @Override
    public void keyPressed(KeyEvent e) {
        int code = e.getKeyCode();

        if (code == KeyEvent.VK_UP) {
            velY = -1;
        }
        if (code == KeyEvent.VK_DOWN) {
            velY = 1;
        }
        if (code == KeyEvent.VK_RIGHT) {
            velX = 1;
        }
        if (code == KeyEvent.VK_LEFT) {
            velX = -1;
        }

    }

    @Override
    public void keyReleased(KeyEvent e) {
        velX = 0;
        velY = 0;
    }

    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }


}   

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:3)

答案是使用Key Bindings而不是KeyListener