【发布时间】:2014-02-09 00:10:04
【问题描述】:
所以我想按照一定的速度移动一个圆圈,比如乒乓球。但我无法更新圈子的位置。这是我的代码,它只会在侧面绘制圆形和矩形。
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 我添加了我的尝试。
标签: java swing jframe paint repaint