Javafx MouseeEvent--将圆添加到场景中

Javafx MouseeEvent--将圆添加到场景中,javafx,Javafx,该程序涉及EventHandler和MouseeEvents的应用程序。该程序的目标是呈现一个空白场景,用户可以左键单击(主)并将圆形对象添加到事件发生时鼠标所在的场景中。可以添加的圈数无关紧要。当用户在目标节点(圆形对象)上悬停时右键单击鼠标(次)时,该对象将从场景中移除。到目前为止,我编写的程序将显示一个圆圈,但只显示在场景的原点,而不是鼠标所在的位置。此外,我只能将一个圆添加到场景中,而不能将其他圆添加到场景中。如果再次单击主圆,我将无法单击次圆并删除位于原点的圆 static Ci

该程序涉及EventHandler和MouseeEvents的应用程序。该程序的目标是呈现一个空白场景,用户可以左键单击(主)并将圆形对象添加到事件发生时鼠标所在的场景中。可以添加的圈数无关紧要。当用户在目标节点(圆形对象)上悬停时右键单击鼠标(次)时,该对象将从场景中移除。到目前为止,我编写的程序将显示一个圆圈,但只显示在场景的原点,而不是鼠标所在的位置。此外,我只能将一个圆添加到场景中,而不能将其他圆添加到场景中。如果再次单击主圆,我将无法单击次圆并删除位于原点的圆

   static Circle circle;    

@Override
public void start(Stage primaryStage) {
    StackPane root = new StackPane();
    Scene scene = new Scene(root, 350, 300);
    primaryStage.setTitle("Dots");
    primaryStage.setScene(scene);

    root.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent me) -> {
        if(me.getButton().equals(MouseButton.PRIMARY)) {
            root.getChildren().add(new Circle(me.getScreenX(), me.getScreenY(), 10, Color.BLUE));
        }
    });

    root.addEventHandler(MouseEvent.MOUSE_ENTERED_TARGET, (MouseEvent me) -> {
        if(me.getButton().equals(MouseButton.SECONDARY)) {
            root.getChildren().remove(me.getTarget());
        }
    });

    primaryStage.show();
}

我不认为使用两个事件处理程序是实现这一点的最佳方式。最初,我在第一个处理程序的if-else语句中有第二个事件处理程序体(root.getChildren)。我之所以更改它,是因为我不确定如何实现MouseEvent.MOUSE\u输入了\u TARGET来指定要从场景中移除的圆对象

我建议您使用
而不是
堆栈窗格
,因为它不会自动排列子节点

要了解更多关于布局行为的信息,我建议您仔细阅读

对于创建的每个圆圈,向其添加一个
EventHandler
,以便对其进行监控
右键单击
,然后将其从中删除
父项

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

public class AddAndRemoveCircles extends Application {

    @Override
    public void start(Stage primaryStage) {
        Group root = new Group();
        Scene scene = new Scene(root, 350, 300);
        primaryStage.setTitle("Dots");
        primaryStage.setScene(scene);

        scene.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent me) -> {
            if(me.getButton().equals(MouseButton.PRIMARY)) {
                Circle circle = new Circle(me.getX(), me.getY(), 10, Color.BLUE);
                addEventHandler(root, circle);
                root.getChildren().add(circle);
            }
        });

        primaryStage.show();
    }

    public void addEventHandler(Group parent, Node node) {
        node.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent me) -> {
            if(me.getButton().equals(MouseButton.SECONDARY)) {
                parent.getChildren().remove(node);
            }
        });
    }
}