JavaFX Rectangle Tutorial

0
JavaFX rectangle class define a Rectangle.

It require three things to draw a Rectangle

  1. Height
  2. Width
  3. Top-left corner coordinates(x,y).

Constructors :

  • Rectangle()Creates an empty instance of Rectangle.
  • Rectangle(double width, double height)Creates a new instance of Rectangle with the given size.
  • Rectangle(double x, double y, double width, double height)Creates a new instance of Rectangle with the given position and size.
  • Rectangle(double width, double height, Paint fill)Creates a new instance of Rectangle with the given size and fill.

Methods used for rectangle:

setStroke() :

To understock the Stroke is just an outline which drawn on any Shape.

setStrock method set the color of the stroke AS

rectangle.setStrock(color.BLACK);

setFill() :

It fill the interior of a Shape with given color AS

rectangle.setFill(Color.BLACK);

It fill the rectangle with black color.

Example of rectangle:


package javafxtuts;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

/**
 *
 * @author JavaFXtuts.com
 */
public class Javafxtuts extends Application {
    
    @Override
    public void start(Stage primaryStage) {
         Pane root = new Pane();
         
        //creating rectangle using empty constructor 
        Rectangle rectangle = new Rectangle();
        rectangle.setX(10);
        rectangle.setY(20);
        rectangle.setWidth(220);
        rectangle.setHeight(160);
        
        // To set outlier color of rectangle to Black
        rectangle.setStroke(Color.BLACK);
        // To set interior color of rectangle to DARKCYAN
        rectangle.setFill(Color.DARKCYAN);
        //To set the width of the stroke using setStrokeWidth()
        rectangle.setStrokeWidth(3);
        root.getChildren().addAll(rectangle);

        Scene scene = new Scene(root, 250, 220);
        
        primaryStage.setTitle("javafxtuts.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
}

Output :

Explain :

  • First create an empty instant of the rectangle as
    Rectangle rectangle = new Rectangle();
  • Then setting the parameter of the rectangle using the setter methods as
    
    rectangle.setX(10);
    rectangle.setY(20);
    rectangle.setWidth(220);
    rectangle.setHeight(160);

    It Draw a rectangle of 220×160 with (10,20) top-left coordinates.

  • At last using setStrokeWidth() set the width of the stroke As
    rectangle.setStrokeWidth(3);
    It set the Stroke width 3.
Share.

Leave A Reply