Hello, I have a problem with a shape generator. It randoms the shapes just fine, I just do not know how to make all the shapes fully stay within the frames border.
RandomShapeMaker.java
import java.awt.Color; import java.awt.Graphics; import javax.swing.JPanel; import java.util.Random; public class RandomShapeMaker extends JPanel{ private static final Random randomShape = new Random(); public void paintComponent( Graphics g ){ super.paintComponent( g ); int width = getWidth(); int height = getHeight(); int shape;//holding the shape Color colour;//holding the colour int x;//holding x coordinate int y;//holding y coordinate int shapeWidth; int shapeHeight; for( int i = 0; i < 100; i++ ){ //determine the coordinates and size of shapes to draw shape = decideShape(); colour = decideColour(); x = decideCoordinates( width ); y = decideCoordinates( height ); shapeWidth = decideSize( width ); shapeHeight = decideSize( height ); g.setColor(decideColour()); //switch statement for shape switch( shape ){ case 1: g.fillOval( x, y, shapeWidth, shapeHeight ); break; case 2: g.fillRect( x, y, shapeWidth, shapeHeight ); break; }//shape switch }//end of for loop }//end of paintComponent method //choose randomly the shape, 1 for oval, 2 for rectangle public static int decideShape(){ int theShape = 1 + randomShape.nextInt(2); // System.out.printf("Shape value returned is %d\n", theShape); return theShape; } //choose randomly the colour public static Color decideColour(){ Color theColour = new Color(randomShape.nextInt(256), randomShape.nextInt(256), randomShape.nextInt(256)); //System.out.printf("Colour value returned is %d\n", theColour); return theColour; } //choose random coordinates, x and y depending on the parameter passed to it public static int decideCoordinates( int origin ){ int coordinate = randomShape.nextInt( origin + 1 ); //System.out.printf("Coordinate value returned is %d\n", coordinate); return coordinate; } //choose random side lenghts public static int decideSize(int dimension){ int side = randomShape.nextInt( dimension / 2 ); //System.out.printf("Coordinate value returned is %d\n", side); return side; } }//end of class Shapes
ShapeGenerator.java
import javax.swing.JFrame; public class ShapeGenerator{ public static void main( String[] args){ RandomShapeMaker panel = new RandomShapeMaker(); JFrame application = new JFrame(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); application.add( panel ); application.setSize( 1500, 800 ); application.setVisible( true ); } }
Regards,
Jing