Final answer:
To make a colored box in JavaFX, create a Rectangle object, set its size, apply a color using setFill, add it to a layout, and then include it in a Scene displayed by a Stage.
Step-by-step explanation:
To create a colored box in JavaFX, you can use the Rectangle class, which is part of the JavaFX shapes library, to draw the box, and then set its fill property to the desired color using the setColor method. Here's a step-by-step guide to achieve this:
- First, create a new Rectangle object.
- Set the width and height of the rectangle to define its size.
- Use the setFill method of the Rectangle to apply a color. You can use the Color class to choose the color for the box.
- Add the rectangle to a layout component, like a StackPane or Group, to include it in your application's scene graph.
- Finally, place the layout containing the rectangle onto a Scene, and set that scene on your application's Stage to display the colored box.
Here is a simple code example:
Rectangle rectangle = new Rectangle(200, 100);
rectangle.setFill(Color.BLUE);
StackPane root = new StackPane();
root.getChildren().add(rectangle);
Scene scene = new Scene(root, 300, 250);
Stage primaryStage = new Stage();
primaryStage.setScene(scene);
primaryStage.show();
This code snippet creates a blue rectangle with a width of 200 pixels and a height of 100 pixels, places it in a StackPane, and then sets up the scene and stage to display the colored box.