0

Suppose I have the following two rectangles and I wanted to delete one:enter image description here

I know how to implement the delete button method, however I do not know how I can select between the shapes through a mouse-click. Could someone please give me some guidelines/examples as to how I would go about this. Thanks

Edit - Where I construct the rectangle:

if (treeview.getSelectionModel().getSelectedItem() == greenrect) {
                Rectangle rect = drag.createDraggableRectangle(200, 60, 200, 60);
                ObjectProperty<Point2D> mousePosition = new SimpleObjectProperty<>();
                GraphicsContext gc = canvas.getGraphicsContext2D();
                rect.setFill(Color.GREEN);
                container2.getChildren().addAll(rect);
                }

1 Answer 1

1

use the same event on both of the shapes like this:

private List<Shape> selectedShapes = new ArrayList<>();
@FXML
public void onShapeSelected(MouseEvent e) {
  Shape shape = (Shape) e.getSource();

  if (!selectedShapes.contains(shape)) {
    selectedShapes.add(shape);
  }
}

@FXML 
public void delete(ActionEvent e) {
   // delelte all the shapes from selected shapes list
}

What i did here is to save the selected nodes inside a list, and when the user will press delete you will be able to delete all the selected nodes. I'm also recommend you to add selected style to the selected shape for notice the user that he selected the Shape and when the user re-press on the shape you can remove the shape from the list (don't forget to also remove the selected style)

Sign up to request clarification or add additional context in comments.

7 Comments

Hey, thanks for your response. What would the "!selectedShapes" be??.. Thanks
array list of shapes for example
I see what your doing. That is great! could you please tell me how I could use the method for my rectangle?. I have added the code where I initialise the green rectangle. The code shows how I add the rectangle to my pane from a treelist. Thanks :D
greenRect.setOnMouseClicked(e -> onShapeSelected(e)); If you're using java 8
Fantastic! Worked a treat! :D
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.