In: Computer Science
Write a JavaFX application that draws 5 squares. Use a random number generator to generate random values for the size, x, and y. Make the size between 100 and 200, x between 0 and 600, y between 0 and 400. You can pick any color, but you must use different colors for the 5 squares. Set your window to 600 by 400.
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
// DrawSquares.java
import java.util.Random;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class DrawSquares extends Application {
//declaring needed measurements
private static int WIDTH = 600, HEIGHT = 400, NUM_SQUARES = 5, SIZE_MIN = 100, SIZE_MAX = 200;
@Override
public void start(Stage primaryStage) {
//creating a Group
Group root = new Group();
//creating a Random number generator
Random random = new Random();
//looping for NUM_SQUARES number of times
for (int i = 0; i < NUM_SQUARES; i++) {
//generating a random size between SIZE_MIN and SIZE_MAX
int size = random.nextInt(SIZE_MAX - SIZE_MIN + 1) + SIZE_MIN;
//creating a square at random x,y point and with size
Rectangle sq = new Rectangle(random.nextInt(WIDTH), random.nextInt(HEIGHT), size, size);
//generating a random color, here the first three values are r,g,b values between 0.0 and 1.0,
//last value 1 is the alpha value (transparency)
sq.setFill(new Color(random.nextDouble(), random.nextDouble(), random.nextDouble(), 1));
//adding sq to root
root.getChildren().add(sq);
}
//setting up a Scene and displaying it
Scene scene = new Scene(root, WIDTH, HEIGHT);
primaryStage.setScene(scene);
primaryStage.setTitle("Squares");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
/*OUTPUT*/