I'm working on a homework that probably everyone that has taken java ends up doing. I have to get a program to draw 10 triangles. The problem I have is that my program is drawing 10 triangles. Then putting up a black background and then drawing 10. If I don't sleep the thread you cannot tell that the first 10 were ever drawn, but it bugs me and I cannot understand why it is doing this.
Thank you in advance for any explanations.Code:import java.awt.*; import java.awt.geom.*; import java.util.Random; import javax.swing.*; public class HW1a extends JFrame { int i,z; int x[] = new int[3]; int y[] = new int[3]; Random rand = new Random(); public HW1a() { super( "Drawing Triangles" ); setSize( 600, 600 ); setVisible( true ); } public void paint( Graphics g ) { super.paint( g ); getContentPane().setBackground(Color.BLACK); Graphics2D g2d = ( Graphics2D ) g; for(z=0; z<10; z++){ //needs to have 10 triangles GeneralPath triangle = new GeneralPath(); for (i=0; i<3; i++) { x[i] = rand.nextInt(600); y[i] = rand.nextInt(600); } triangle.moveTo( x[ 0 ], y[ 0 ] ); for ( int count = 1; count < x.length; count++ ) triangle.lineTo( x[ count ], y[ count ] ); triangle.closePath(); g2d.setColor( new Color(rand.nextInt(256),rand.nextInt(256),rand.nextInt(256))); g2d.fill( triangle ); try { // sleep for 50 ms. Thread.sleep( 50 ); } catch ( Exception e ) {} } } public static void main(String[] args) { HW1a application = new HW1a(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } }




Reply With Quote