gpt4 book ai didi

Java GUI - 移动一个没有 "footprints"的圆

转载 作者:行者123 更新时间:2023-12-01 18:51:21 29 4
gpt4 key购买 nike

当我运行程序并移动圆圈时,看起来就像我在用画笔在油漆中绘画一样。我不太确定我做了什么才能做到这一点,或者我能做些什么来阻止它。非常感谢所有帮助。

这是我的代码:

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);
}


}

最佳答案

您正在调用 super.paintComponents(g); 而不是 super.paintComponent(g);

关于Java GUI - 移动一个没有 "footprints"的圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15826112/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com