You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaFX添加Button至根节点时卡顿问题的原因分析与解决

JavaFX首次添加Button组件卡顿问题(macOS Monterey)

我用JavaFX复刻Flappy Bird游戏,在macOS Monterey系统下遇到以下问题:

  • 小鸟首次死亡,游戏结束GUI出现前会短暂卡顿;但不停止程序、直接重启游戏后,再次死亡则不会卡顿。
  • 已定位卡顿根源:向根节点添加Button组件,移除Button后卡顿完全消失。

我写了简化代码复现该问题:首次运行时,包含移动矩形与Restart按钮的节点加载需1-2秒;点击Restart按钮后节点可流畅重现;注释Button节点则全程无卡顿。简化代码如下:

public class Main extends Application{

    Group root;

    @Override
    public void start(Stage stage) {
        root = new Group();
        Scene scene = new Scene(root, 400, 400);
        stage.setScene(scene);
        stage.show();

        game();
    }

    public void game(){
        root.getChildren().clear();

        Rectangle bird = new Rectangle(40, 40, Color.BLACK);
        bird.setX(0);
        root.getChildren().add(bird);

        AnimationTimer timer = new AnimationTimer(){

            @Override
            public void handle(long l) {
                bird.setX(bird.getX() + 1);
            }
        };

        timer.start();

        Button btn = new Button("Restart");
        btn.setLayoutX(200);
        btn.setLayoutY(200);
        root.getChildren().add(btn);

        btn.setOnAction(event -> {
            timer.stop();
            game();
        });
    }

}

内容的提问来源于stack exchange,提问作者ycz_425

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 16:34:56