Reputation: 79
I'm very new to this so bear with me. I've made an applet that produces a fan shape starting in the upper left-hand corner of the frame (0,0). The program draws 200 randomly colored lines moving from the top to the bottom of the applet. It them reverses the process and leaves you with a blank applet frame. I want to have this iterate 5 times however my attempts at using a for-loop have not been successful.
The code I'm using in the for loop is: for (int times = 0; times < 5; times++) { if (painting)
I have a Boolean in the Main class for painting. boolean painting=true;
I've resorted to repeating the code 5 times, but I know there should be a better way using a for-loop.
My code with the 5 repeats:
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);
}
}
}
I also have the wait class:
public class Wait{
public static void holdOn(long period){
try{
Thread.sleep(period);
}catch(Exception e){}
}
}
Upvotes: 0
Views: 874
Reputation: 347294
Do not, ever, wait within a paint
method...or the Event Dispatching Thread. This will simply make your program look like's stuttering...
Take a look at Concurrency in Swing and How to Use Swing Timers...
You should also ensure that you are calling super.paint
before you perform any kind of painting! In fact, you should avoid overriding paint
, as this will cause your updates to flicker, instead create a custom component, from something like JPanel
and override it's paintComponent
method, see Performing Custom Painting for more details...
Upvotes: 2