Hey everyone! I have to write a program that generates random shapes in a window, but when the window is resized the program can still remember the shapes and redraw the same ones.
My code so far draws the random shapes, but when I resize the window, the shapes change into new ones. Any help!?
This is what I have as my Picture class:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
import java.util.Random;
public class Picture extends JPanel {
//chooses at random
private static final Random randomShape = new Random();
public void paintComponent (Graphics g){
super.paintComponent( g );
int width = getWidth();
int height = getHeight();
int shape;
int color;
int x; //x coordinate
int y; //y coordinate
int shapeWidth;
int shapeHeight;
for( int i = 0; i < 10; i++ ){
//chooses the coordinates and size of the shapes
shape = ChoosesShape1();
color = ChoosesColor1();
x = ChoosesCoordinates1( height );
y = ChoosesCoordinates1( width );
shapeHeight = ChoosesSize1( height );
shapeWidth = ChoosesSize1( width );
//switch statement for size
switch (shape){
case 1:
g.fillOval(x, y, shapeWidth, shapeHeight);
break;
case 2:
g.fillRect(x, y, shapeWidth, shapeHeight);
break;
}
//The are my switch statements for the shape colors
switch(color){
case 1:
g.setColor( Color.GRAY);
break;
case 2:
g.setColor( Color.PINK);
break;
case 3:
g.setColor( Color.LIGHT_GRAY);
break;
case 4:
g.setColor( Color.DARK_GRAY);
break;
case 5:
g.setColor( Color.BLUE);
break;
case 6:
g.setColor( Color.YELLOW);
break;
case 7:
g.setColor( Color.MAGENTA);
break;
case 8:
g.setColor( Color.RED);
break;
case 9:
g.setColor( Color.GREEN);
break;
case 10:
g.setColor( Color.BLACK);
break;
}
}
}
public static int ChoosesShape1(){
int theShape = 1 + randomShape.nextInt(2);
return theShape;
}
public static int ChoosesColor1(){
int theColor = 1 + randomShape.nextInt(10);
return theColor;
}
public static int ChoosesCoordinates1( int origin ){
int coordinate = randomShape.nextInt( origin + 1 );
return coordinate;
}
public static int ChoosesSize1(int dimension){
int side = randomShape.nextInt( dimension / 2 );
return side;
}
}