首页 > 解决方案 > JavaFX。淡化过渡。单击后如何从组中删除对象?

问题描述

我正在研究国际象棋应用程序。想要使用 Canvas 对象在板上实现 Piece 的选择。预期行为:用户单击 Piece,Canvas 对象出现在板上,并在 1000 毫秒内消失。想要从组中删除此画布选择,一旦它消失。因为现在不可能第二次点击并看到这个选择。

如果单击 Rectangle,此代码将创建 Rectangle 和 Canvas 对象,但只创建一次。第二次点击被忽略。尝试插入group.getChildren().remove(selection);但没有成功。你能告诉我我做错了什么吗?非常感谢您的帮助

package Board.fileManagement;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.animation.FadeTransition;
import javafx.util.Duration;
import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Rectangle;

public class Test extends Application {


    @Override
    public void start(Stage primaryStage) throws Exception {

        Rectangle rect1 = new Rectangle(200, 200, 120, 120);
        rect1.setArcHeight(42);
        rect1.setArcWidth(42);
        rect1.setFill(Color.AQUA);

        Group group = new Group();
        group.getChildren().addAll(rect1);
        Scene scene = new Scene(group, 600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();

        rect1.setOnMousePressed(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                Canvas selection = new Canvas(1000, 1000);
                GraphicsContext gc = selection.getGraphicsContext2D();
                gc.setStroke(Color.BLUE);
                gc.setLineWidth(20);
                gc.strokeRoundRect(160, 160, 200, 200, 50, 50);

                FadeTransition ft = new FadeTransition(Duration.millis(1000), selection);
                ft.setFromValue(1.0);
                ft.setToValue(0.0);
                ft.play();
                group.getChildren().add(selection);
            }
        });

    }

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

标签: animationjavafxmouseevent

解决方案


推荐阅读