我一直试图解决这个问题几个小时了,我似乎无法弄明白。我的最终目标是拥有一个内部有移动球的JFrame。我遇到的问题是当我的精灵移动时,留下一条痕迹。这是一个image of what the JFrame looks like。请原谅我对GUI组件的极其有限的了解,因为这是我第一次使用它们。这是我的课程。非常感谢任何帮助,因为我真的很困惑。
公共类TenBall {private int XPos;
private int YPos;
Image theBall = Toolkit.getDefaultToolkit().getImage("src//ball2.jpeg");
public TenBall(int x,int y) {
YPos = y;
XPos = x;
}
public int getXPos(){
return XPos;
}
public int getYPos() {
return YPos;
}
//400,500
public void move() {//this method moves the ball and doesn't let it touch the sides of the JFrame
XPos++;
if(XPos >= 390) {
XPos --;
}
if(XPos <= 10) {
XPos++;
}
if(YPos >=490) {
YPos--;
}
if(YPos <=10) {
YPos++;
}
}
public void draw(Graphics g) { //this is the paint method called in gameWindow
g.drawImage(theBall, (int)XPos, (int)YPos, null);
}
import java.awt.*;
公共类GameAnimation扩展了线程{
private TenBall MyBall;
private gameWindow theWindow;
public GameAnimation(TenBall b, gameWindow win) {
MyBall = b;
theWindow=win;
}
public void run() {
int t=0;
while(t<1000) {
MyBall.move();
theWindow.repaint();
try{
Thread.sleep(2);
}
catch (InterruptedException ex)
{
}
}
}
}
现在是GameWindow类
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class gameWindow extends JFrame{
public TenBall ATB;
public gameWindow() {
this.setVisible(true);
this.setTitle("Chase the Ball Game");
this.setSize(400,500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = this.getContentPane();
c.setBackground(Color.red);
ATB = new TenBall(50,50);
JPanel myPanel=new JPanel();
this.getContentPane().add(myPanel);
startGame();
}
public void paint(Graphics g){
ATB.draw(g);
}
public void startGame() {
GameAnimation Thread1 = new GameAnimation(ATB, this);
Thread1.start();
ATB.move();
}
public static void main(String[] args) {
new gameWindow();
}
}