Tuesday, April 24, 2007

Draw stars using Java

Here is a tutorial to make your way into drawing graphics with Java. This program creates a semi-circle line of stars. The stars are randomly colored. I made the program using Netbeans 5.5, and I tested the code also with Sun Java Studio Enterprise 8.1. Both of them are free. The output is what you see above (star color may differ as they are randomly colored).
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.geom.*;

class psy2k extends JFrame {
public psy2k()
{
super( "Psy2k star draw" );

setBackground( Color.white );
setSize( 400, 400 );
show();
}
public void paint( Graphics g )
{
int xPoints[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };
int yPoints[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };

Graphics2D g2d = ( Graphics2D ) g;

GeneralPath star = new GeneralPath();
star.moveTo( xPoints[ 0 ], yPoints[ 0 ] );

for ( int k = 1; k < xPoints.length; k++ ) star.lineTo( xPoints[ k ], yPoints[ k ] ); star.closePath();
g2d.translate( 200, 200 );
for ( int j = 1; j <= 20; j++ ) {
g2d.rotate( Math.PI / 20.0 );
g2d.setColor( new Color( ( int ) ( Math.random() * 256 ),
( int ) ( Math.random() * 256 ),
( int ) ( Math.random() * 256 ) ) );
g2d.fill( star );
}
}
public static void main( String args[] )
{
psy2k app = new psy2k();
app.addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}

3 comments:

John said...

Great stuff! Enjoy bro :)

James said...

Hi,
My name is James Branam and I'm the NetBeans Community Docs Manager. Your blog entry would make a fantastic tutorials for our Community Docs wiki (http://wiki.netbeans.org/wiki/view/CommunityDocs). Would you be willing to contribute it? If you need any help or have any questions, please contact me at james.branam@sun.com. I look forward to hearing from you.

James said...

Hi,
My name is James Branam and I'm the NetBeans Community Docs Manager. Your blog entry would make a fantastic tutorials for our Community Docs wiki (http://wiki.netbeans.org/wiki/view/CommunityDocs). Would you be willing to contribute it? If you need any help or have any questions, please contact me at james.branam@sun.com. I look forward to hearing from you.