我對此非常陌生,所以請耐心等待。我製作了一個小程序,可以從幀的左上角開始生成扇形(0,0)。該程序從小程序的頂部到底部繪製200條隨機彩色線條。它們顛倒了過程,並留下了一個空白的小程序框架。我想要迭代5次,但是我嘗試使用for循環並沒有成功。Java小程序For-Loop在5次迭代後停止繪製
我使用在for循環中的代碼是: 對(INT倍= 0;倍< 5;倍++){ 如果(畫)
我有一個布爾在用於繪製的主要類。 boolean painting = true;
我已經採取了重複代碼5次,但我知道應該有一個更好的方式使用for循環。
我與5個重複碼:
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JApplet;
public class Main extends JApplet {
private static Random rand = new Random();
public void init() {
setBackground(Color.WHITE);
setSize(400, 300);
}
public void paint(Graphics g) {
for (int i = 0; i < 200; i++) {
Wait.holdOn(10);
g.setColor(new Color(rand.nextInt(0xFFFFFF)));
g.drawLine(0, 0, 200 - i, i);
}
for (int i = 0; i < 200; i++) {
Wait.holdOn(10);
g.setColor(getBackground());
g.drawLine(0, 0, i, 200 - i);
}
for (int i = 0; i < 200; i++) {
Wait.holdOn(10);
g.setColor(new Color(rand.nextInt(0xFFFFFF)));
g.drawLine(0, 0, 200 - i, i);
}
for (int i = 0; i < 200; i++) {
Wait.holdOn(10);
g.setColor(getBackground());
g.drawLine(0, 0, i, 200 - i);
}
for (int i = 0; i < 200; i++) {
Wait.holdOn(10);
g.setColor(new Color(rand.nextInt(0xFFFFFF)));
g.drawLine(0, 0, 200 - i, i);
}
for (int i = 0; i < 200; i++) {
Wait.holdOn(10);
g.setColor(getBackground());
g.drawLine(0, 0, i, 200 - i);
}
for (int i = 0; i < 200; i++) {
Wait.holdOn(10);
g.setColor(new Color(rand.nextInt(0xFFFFFF)));
g.drawLine(0, 0, 200 - i, i);
}
for (int i = 0; i < 200; i++) {
Wait.holdOn(10);
g.setColor(getBackground());
g.drawLine(0, 0, i, 200 - i);
}
for (int i = 0; i < 200; i++) {
Wait.holdOn(10);
g.setColor(new Color(rand.nextInt(0xFFFFFF)));
g.drawLine(0, 0, 200 - i, i);
}
for (int i = 0; i < 200; i++) {
Wait.holdOn(10);
g.setColor(getBackground());
g.drawLine(0, 0, i, 200 - i);
}
}
}
我也有等待類:
public class Wait{
public static void holdOn(long period){
try{
Thread.sleep(period);
}catch(Exception e){}
}
}
不要,永遠,在'paint'方法內或者Event Dispatching Thread中等待。這隻會讓你的程序看起來像口吃...看看[併發在Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/)和[如何使用Swing定時器]( http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html)...Oh,並調用'super.paint'! – MadProgrammer