How do I add an image inside a rectangle or a circle in JavaFX?


Question

Suppose we have a rectangle called r

Rectangle r = new Rectangle(40, 20);

and an image called image

Image image = new Image("...src for image");

How do I fit the image inside the rectangle? Also, how can I make the image move if the rectangle moves too? How do I do the same thing for a circle? Code examples are greatly appreciated.

P.S. Jewelsea, I'm waiting for you, lol!

1
4
4/3/2014 8:55:45 PM

Accepted Answer

if you want to fill Rectangle by image, you can follow this:- in your fxml file add a Circle

<Rectangle fx:id="imgMenuUser" />

And in your Controller

@FXML
private Rectangle rectangle;
Image img = new Image("/image/rifat.jpg");
rectangle.setFill(new ImagePattern(img));
10
6/16/2015 10:03:02 PM

How do I fit the image inside the rectangle?

Put the shape and the image in a StackPane.

Also, how can I make the image move if the rectangle moves too?

Just move the StackPane.

import javafx.application.Application;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Point2D;
import javafx.stage.Stage;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;


public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {
            Pane root = new Pane();

            StackPane imageContainer = new StackPane();
            ImageView image = new ImageView(...);
            imageContainer.getChildren().addAll(new Rectangle(64, 48, Color.CORNFLOWERBLUE), image);
            enableDragging(imageContainer);

            root.getChildren().add(imageContainer);

            Scene scene = new Scene(root,800,600);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    private void enableDragging(Node node) {
        final ObjectProperty<Point2D> mouseAnchor = new SimpleObjectProperty<>();
        node.setOnMousePressed( event -> mouseAnchor.set(new Point2D(event.getSceneX(), event.getSceneY())));
        node.setOnMouseDragged( event -> {
            double deltaX = event.getSceneX() - mouseAnchor.get().getX();
            double deltaY = event.getSceneY() - mouseAnchor.get().getY();
            node.relocate(node.getLayoutX()+deltaX, node.getLayoutY()+deltaY);
            mouseAnchor.set(new Point2D(event.getSceneX(), event.getSceneY()));;
        });
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon