javajavafxmouseevent

JavaFX problem with drawing a polygon in the right place


I have the following problem: Drawing a figure (in this case a triangle) works correctly. However, the triangle should be drawn where I clicked, and it starts drawing from the upper left corner of the toolBar and this should not happen.

I am also attaching a link to my Google Drive with a recording showing that the triangle is drawn in the wrong place after 3 clicks. : paint recording

public class Controller {
    @FXML
    private Button triangleButton;
    @FXML
    private Button rectangleButton;
    @FXML
    private Button circleButton;
    @FXML
    private HBox hBox;
    private int triangleCounter = 0, rectangleCounter = 0, circleCounter = 0;
    private ArrayList<Double> xPoints = new ArrayList<>();
    private ArrayList<Double> yPoints = new ArrayList<>();

    
    @FXML
    public void onButtonClicked(ActionEvent e) {
        ArrayList<Button> buttons = new ArrayList<Button>();
        buttons.add(triangleButton);
        buttons.add(rectangleButton);
        buttons.add(circleButton);

        for (Button btn:buttons)
            btn.setDisable(true);

         if (e.getSource().equals(triangleButton)) {

                hBox.setOnMouseClicked(event -> {
                    double x = event.getX();
                    double y = event.getY();
                    xPoints.add(x);
                    yPoints.add(y);
                    triangleCounter += 1;
                    if (triangleCounter >= 3) {
                        for (Button btn : buttons)
                            btn.setDisable(false);
                        triangleCounter = 0;
                        MyTriangle triangle = new MyTriangle(xPoints.get(0),yPoints.get(0),
                                xPoints.get(1),yPoints.get(1), xPoints.get(2), yPoints.get(2));
                        triangle.drawTriangle();
                        hBox.getChildren().add(triangle);
                        hBox.setOnMouseClicked(null);
                    }
                });
        } 
        xPoints.clear();
        yPoints.clear();
    }
}

Thank you in advance for your help


Solution

  • HBox is a managed layout container. If you want to perform free-form drawing, you should not be using a managed layout container. Instead, you should be using a Group or Pane that does not perform layout on your behalf (as you don't want that to occur).

    If you have managed layout for controls like buttons, they should be in a separate container from your free-form drawing container.

    Simple drawing app for reference. That example uses a Canvas, but you can use the Scene Graph instead, just ensure that you aren't drawing into a pane style that manages your layout for you.