PDA

Click to See Complete Forum and Search --> : Java2D and Graphics. Please Help . I am beginner


datab
Apr 25th, 2002, 09:44 PM
I need to display randomly generated triangles in different colors. Each triangle should be filled with different color. use class GeneralPath and fill of class Graphics2D to draw triangles.

Here is the code I have written. Its not working correctly.

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

import javax.swing.*;

public class Triangles extends JFrame
{
public Triangles()
{
super( "Drawing 2d shapes" );

getContentPane().setBackground( Color.black );
setSize( 400, 400 );
setVisible( true );
}

public void paint( Graphics g )
{
super.paint( g );


int xP, yP, zP;

Graphics2D g2d = ( Graphics2D ) g;

GeneralPath triangle = new GeneralPath();



for( int count = 1; count <= 5; count++ )
{
xP = ( int ) ( Math.random() * 256 );
yP = ( int ) ( Math.random() * 256 );
zP = ( int ) ( Math.random() * 256 );


triangle.moveTo( xP, yP );

triangle.lineTo( ( int ) ( Math.random() * 400 ), ( int ) ( Math.random() * 150 ) );

triangle.lineTo( ( int ) ( Math.random() * 400 ), ( int ) ( Math.random() * 150 ) );

triangle.closePath();


g2d.setColor( new Color( xP, yP, zP ) );


g2d.fill( triangle );
}

}

public static void main( String args[] )
{

Triangles application = new Triangles();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}



Thank you

VirtuallyVB
May 4th, 2002, 07:18 PM
This smells like homework.

Anyway, move the statement
GeneralPath triangle = new GeneralPath();
to within the for loop and somewhere before the
triangle.moveTo( xP, yP );
statement. Right at the beginning of the loop is fine.

...
for( int count = 1; count <= 5; count++ )
{
GeneralPath triangle = new GeneralPath();

xP = ( int ) ( Math.random() * 256 );
yP = ( int ) ( Math.random() * 256 );
zP = ( int ) ( Math.random() * 256 );

triangle.moveTo( xP, yP );
...


I would also have the random vertices span the size of the window. You have the size as 400X400 but only span 400X150 (keeping the triangle in the upper region of your window). Change the 150 to 400 in both
triangle.lineTo
statements. Also, why didn't you choose the first point
triangle.moveTo( xP, yP );
in the random region 400X400? You are being lazy by using the color components xP and yP whose range spans from 0 to 255 instead of a third point in the entire region 400X400.
So you can change
triangle.moveTo( xP, yP );
to
triangle.moveTo( ( int ) ( Math.random() * 400 ), ( int ) ( Math.random() * 400 ) );

Also, if you minimize the window and then maximize it, you will see a new set of triangles. But if you partially cover the window with say another window, then uncover it, you will get a new set which can only be seen through the region that was "covered then uncovered".

Hope this assignment isn't too late. ;)

datab
May 6th, 2002, 09:03 PM
Thank you very much. I figured out my mistakes.