Java定时器中的摆动变化延迟
我试图编辑我的计时器,这样每25次重新绘制()就被称为计时器触发速度减半。所以前25次是500次;接下来的25倍是250倍;等等
两个“经验丰富者容易”的问题:
1)为什么Eclipse让我将变量设置为静态(或者不编译)
2)程序似乎没有达到我将速度一分为二并将延迟设置为新速度的功能。为什么?我该怎么修
public class MovingCircle extends JFrame implements ActionListener {
Ellipse2D.Double myEllipse;
Rectangle2D.Double backgroundRectangle;
private static int paintCount = 0;
private static int speed = 500;
public MovingCircle() {
//Make the ellipse at the starting position
myEllipse = new Ellipse2D.Double( 30, 30, 20, 20 );
//Make the background rectangle to "erase" the screen
backgroundRectangle = new Rectangle2D.Double( 0, 0, 400, 300 );
}
public static void main(String[] args ) {
MovingCircle b = new MovingCircle();
b.setSize( 400, 300 );
b.setVisible(true);
b.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
Timer t = new Timer(500, b );
t.start();
if(paintCount % 25 == 0) {
t.setDelay((int)(speed / 2));
speed = (int)(speed / 2);
System.out.println(speed);
}
}
public void actionPerformed( ActionEvent ae ) {
//This will be called by the Timer
myEllipse.setFrame( myEllipse.getX()+1, myEllipse.getY()+1, myEllipse.getWidth(), myEllipse.getHeight());
//Move 1 x-pixel and 1 y-pixel every 50 milliseconds ^
repaint();
}
public void paint(Graphics g) {
paintCount++; // Incremenets by one for every repaint().
System.out.println(paintCount);
int isPaintTen = (int)(paintCount / 10); // Divid current count by 10.
Graphics2D g2 = (Graphics2D)g;
if((isPaintTen % 2) == 0){ // Take modulus to set if #/10 is odd or even.
g2.setColor( Color.YELLOW );
g2.fill( backgroundRectangle );
g2.setColor( Color.RED );
g2.draw( myEllipse );
}
else if((isPaintTen % 2) == 1) {
g2.setColor( Color.RED );
g2.fill( backgroundRectangle );
g2.setColor( Color.YELLOW);
g2.draw( myEllipse );
}
}
}
# 1 楼答案
在您的示例中,
paintCount
和speed
必须是静态的,因为您在方法main()
中使用它们,而方法本身是静态的,没有实例。为了避免使它们成为静态的,可以将它们引用为b.paintCount
和b.speed
修改计时器的代码需要移到
paint()
方法中。这意味着您的计时器实例将需要成为一个实例变量,您可能应该在构造函数中创建并启动计时器。顺便说一句,这些更改还要求paintCount
和speed
也被设置为“非静态”你应该以这样的方式结束: