DrawStars

Draw Stars with NetBeans

by Nikolaos Maounis (aka Nikos Psy2k)

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 in the image (star color may differ as they are randomly colored).

Sample Image

The Code:

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.geom.*;
import java.util.Random;

class psy2k extends JFrame {
    static final Random rand = new Random();

    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( rand.nextInt( 256 ), 
                                     rand.nextInt( 256 ), 
                                     rand.nextInt( 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 ); 
                } 
            } 
        ); 
    }
}

Tutorial by Nikolaos Maounis (aka Nikos Psy2k) Personal Blog

Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo