2
所以我想按照一定的速度移动一个圆圈,比如pong。但我在更新圈子的位置时遇到问题。这是我的代码,只会在一边绘制圆形和矩形。更新JFrame中圆的位置
import java.awt.*;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Game extends JFrame{
public Game(){
GameScreen p1 = new GameScreen();
add(p1);
Timer t = new Timer(1000, new ReDraw());
t.start();
}
public static void main(String[] args){
Game g = new Game();
g.setLocation(400, 200);
g.setSize(700, 600);
g.setVisible(true);
}
}
class ReDraw implements ActionListener{
static int count = 0;
static int posX = 603;
static int posY = 210;
static int velX = 50;
static int velY = 50;
public void actionPerformed(ActionEvent e){
count++;
posX -= velX;
posY -= velY;
System.out.println("Flag 1: " + posX + " " + posY);
if (count == 2)
((Timer)e.getSource()).stop();
}
}
class GameScreen extends JPanel{
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.orange);
g.fillRect(654, 200, 30, 100);
g.setColor(Color.red);
g.fillOval(ReDraw.posX, ReDraw.posY, 50, 50);
}
}
我想使用Timer类摆动,但如果你有另一种方式,我很乐意听到它。
编辑:我增加了一个尝试更新圆的位置。
@AndrewThompson我加了我的尝试。 –