0

当我运行程序并移动圆圈时,看起来好像我正在用画笔在油漆中绘画。我不太确定我做了什么来做到这一点,或者我能做些什么来让它停止。高度赞赏所有帮助。

这是我的代码:

import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.JPanel;
import java.awt.event.KeyListener;


public class MovingCar extends JPanel implements ActionListener, KeyListener {

    Timer tm = new Timer(5, this);
    int x = 0, y = 0, velX = 0, velY = 0;

    public MovingCar()
    {
        tm.start();
        addKeyListener(this);
        setFocusable(true);
        setFocusTraversalKeysEnabled(false);
    }
    protected void paintComponent (Graphics g) {
        super.paintComponents(g);
        g.drawOval(x, y, 50, 50);
    }

    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_DOWN)      {
            velX = -1;
            velY = 0;
        }

        if (c == KeyEvent.VK_UP)
        {
            velX = 1;
            velY = 0;
        }


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

        if (x < 0)
        {
            velX = 0;
            x = 0;
        }

        if (x > 600)
        {
            velX = 0;
            x = 0;
        }


        repaint();  
        velY = 0;
        velX = 0;

    }


    public static void main(String[] args) {
        MovingCar o = new MovingCar();
        JFrame jf = new JFrame();
        jf.setTitle("Circle Move");
        jf.setSize(600,400);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.add(o);
        jf.setVisible(true);
    }


}
4

1 回答 1

4

你打电话super.paintComponents(g);而不是super.paintComponent(g);

于 2013-04-05T04:53:22.553 回答