Treeno1
Treeno1

Reputation: 139

Moving multiple rectangles around a scene after created with a button

I have a scene, with a button; once pushed the button creates new rectangle object. The shape is draggable, however only the most recent one created can be dragged?

here is the code -

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class RectanglesCirclesDrawing extends Application
{
    Rectangle rect;
    Button button;
    public static void main(String [] args)
    {
         launch(args);
    }
    public void start(Stage primaryStage)
    {
        Pane root = new Pane();
        button = new Button("press me to create a new rectangle!");

        // Creating a new rectangle
        button.setOnAction(e ->{
            rect = new Rectangle();
            rect.setHeight(200);
            rect.setWidth(400);
            root.getChildren().add(rect);
        });

        root.setOnMouseDragged(e ->{
            rect.setX(e.getX());
            rect.setY(e.getY());
        });


        root.getChildren().addAll(button);
        Scene scene = new Scene(root,800,800);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Creating Shapes");
        primaryStage.show();
    }
}

How am i able to get round it?

Upvotes: 0

Views: 456

Answers (1)

XaolingBao
XaolingBao

Reputation: 1044

Well... You are essentially calling

  root.setOnMouseDragged(e ->{
        rect.setX(e.getX());
        rect.setY(e.getY());
    });

so if you drag the root it will set rect x and y to e's x and y, so it's as if you are dragging a rectangle by clicking it, but you're really clicking your root, which means you can click anywhere in your stage, an it will drag the rectangle.

The issue is

button.setOnAction(e ->{
    rect = new Rectangle();
   ...

you are setting rect to a new Rectangle each time, and then you are trying to move only that rectangle.

What you will want to do is add rect.setOnMouseDragged()........ at some point, before creating the next Rect object.

This should be the gist of it, good luck!

Upvotes: 1

Related Questions