Robotics C++ Physics II AP Physics B Electronics Java Astronomy Other Courses Summer Session  

Java2D Class

 

Example

Exercises

 

Starburst Example using

 

  JFrame

  casting to a 2d object

  Random Number Generator class

  translate method

  scale method

 

 

 

 

import java.awt.*;                                                        //for colors and fonts

import java.awt.geom.*;                                              //provides Java2D classes for geometry

import javax.swing.*;                                                  //to use JFrame

import java.util.Random;                                            //to use the Random class

 

public class Primitives2 extends JFrame             //JFrame provides a window

{

    public static void main (String[]args)

    {

          Primitives2 graphicsObject  = new Primitives2();

          //graphicsObject.setBackground(Color.black);          

          graphicsObject.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

    }

    Primitives2() //constructor, called when object created in main

    {

         super("Star Burst");

          setSize(400,400);                                                 //Creating a Java (not Windows) window

          setVisible(true);                                                   //Default is false - not visible

    }

 

    //Note use of Graphics 2D below - needed for scale method

    public void paint (Graphics g)                              //called after constructor finishes

     {

          Graphics2D g2d = (Graphics2D) g;                   //creating an object of 2D class - casting the g object

          g2d.translate (200.0,200.0);                               //translate the origin to 200, 200

          g2d.scale (1.0, -1.0);                                           //positive direction is now up

          Random randomNumber = new Random();     //create an object of Random class

          for (int i = 0; i < 200; i++)

          {

                Color c = new Color(randomNumber.nextInt(255), randomNumber.nextInt(255), randomNumber.nextInt(255));

                g.setColor(c);

                //returns a random number

                int x2 = randomNumber.nextInt();

               int y2 = randomNumber.nextInt();

                g.drawLine(0,0, x2, y2);

          }

    }

}

 

 

Exercises

 

Exercise 1

 

Duplicate the following