How to add image patterns to nodes in JavaFX?


You can apply colors to geometrical shapes in JavaFX using the setFill() and setStroke() methods. The setFill() method adds color to the interior area of the shape whereas the setStroke() method applies color to the boundary of the node.

Both methods accept an object of the javafx.scene.paint.Paint class as a parameter. It is the base class for the color and gradients that are used to fill the shapes and backgrounds with color.

The javafx.scene.paint.ImagePattern class in JavaFX is a subclass of the Paint and using this you can fill a shape with an image.

To apply image pattern to a geometrical shape −

  • Create an Image by instantiating the Image class.

  • Instantiate the ImagePattern class bypassing the image created above, to the constructor (along with other values) as a parameter.

  • Set the created image pattern to the shape using the setFill() method.

Example

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.scene.paint.ImagePattern;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
public class ImagePatterns extends Application {
   public void start(Stage stage) {
      //Drawing a circle
      Circle circle = new Circle(75.0f, 65.0f, 40.0f );
      //Drawing a Rectangle
      Rectangle rect = new Rectangle(150, 30, 100, 65);
      //Drawing an ellipse
      Ellipse ellipse = new Ellipse(330, 60, 60, 35);
      //Drawing Polygon
      Polygon poly = new Polygon(410, 60, 430, 30, 470, 30, 490, 60, 470, 100, 430, 100 );
      //Creating the pattern
      Image map = new Image("http://www.tutorialspoint.com/images/tp-logo.gif");
      ImagePattern pattern = new ImagePattern(map, 20, 20, 40, 40, false);
      //Setting the pattern
      circle.setFill(pattern);
      circle.setStrokeWidth(3);
      circle.setStroke(Color.CADETBLUE);
      rect.setFill(pattern);
      rect.setStrokeWidth(3);
      rect.setStroke(Color.CADETBLUE);
      ellipse.setFill(pattern);
      ellipse.setStrokeWidth(3);
      ellipse.setStroke(Color.CADETBLUE);
      poly.setFill(pattern);
      poly.setStrokeWidth(3);
      poly.setStroke(Color.CADETBLUE);
      //Setting the stage
      Group root = new Group(circle, ellipse, rect, poly);
      Scene scene = new Scene(root, 600, 150);
      stage.setTitle("Setting Colors");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

Updated on: 16-May-2020

784 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements