gpt4 book ai didi

java - 在不知道其引用的情况下删除 Shape (javafx)

转载 作者:行者123 更新时间:2023-12-02 02:55:06 24 4
gpt4 key购买 nike

我想通过左键单击在光标处创建一个圆圈(这有效)并通过右键单击删除光标下方的圆圈(这不起作用)。

我的问题是,我不知道如何在没有引用(其名称)的情况下访问圆,因为所有圆都是在运行时创建的。我听说泛型可以解决我的问题,但我并不真正理解它们。如果还有其他方法请告诉我。

这是代码:

public class circle extends Application {

@Override
public void start(Stage stage) {

Group root = new Group();
Scene scene = new Scene(root, 600, 600, Color.ALICEBLUE);

scene.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {

if(event.getButton() == MouseButton.PRIMARY) {
root.getChildren().add(new Circle(event.getSceneX(), event.getSceneY(), 10, Color.DARKCYAN));
}

// Does not work. It should delete the circle below the cursor
if(event.getButton() == MouseButton.SECONDARY) {
root.getChildren().remove((int)event.getSceneX(), (int)event.getSceneX());
}
}
});

stage.setScene(scene);
stage.setTitle("Thx for helping me :)");
stage.show();
}

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

如果我误解了“引用”一词,我很抱歉。我认为它是您在创建对象时为其指定的名称。 ( Circle "reference"= new Circle(); )

谢谢你帮助我!

最佳答案

直接用圆圈注册右键监听:

scene.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {

if(event.getButton() == MouseButton.PRIMARY) {
Circle circle = new Circle(event.getSceneX(), event.getSceneY(), 10, Color.DARKCYAN);
circle.setOnMouseClicked(e -> {
if (e.getButton() == MouseButton.SECONDARY) {
root.getChildren().remove(circle);
}
});
root.getChildren().add(circle);
}


}
});

关于java - 在不知道其引用的情况下删除 Shape (javafx),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43240007/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com