我試圖編輯我的定時器,以便每25次重繪()稱爲定時器啓動速度減半。所以前25次是500。那麼下一個25倍的250;等等。在Java定時器中更改延遲
兩個'EASY對於有經驗的'問題:
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);
}
}
}
這將是更容易爲「有經驗」,以幫助你,如果你願意花時間來修復你的代碼示例的縮進所以我們可以不用花括號來閱讀它。 – Lee 2010-09-13 07:07:47