JavaFX GUI不释放内存 [英] JavaFX GUI doesn't release memory

查看:856
本文介绍了JavaFX GUI不释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几周来一直在努力解决JavaFX应用程序中的内存泄漏问题,并且今天认为我完全失去了它所以决定编写我能想到的最简单的应用程序应用程序来证明JavaFX实际上可以发布记忆,因此证明我做错了什么。令我惊讶的是,这似乎也在泄漏记忆。

I've been struggling for weeks to resolve the memory leaks within our JavaFX application, and thought today I was at a complete loss with it so decided to write the simplest application application I could think of to prove JavaFX could in fact release memory and therefore proving I was doing something wrong. To my surprise this seems to leak memory too.

任何人都可以建议为什么以下应用程序在堆中之后仍然有一个 javafx.scene.control.Label 单击按钮?我检查它的方式是使用jprofiler。

Can anyone advise why the following application still has a javafx.scene.control.Label in the heap after the button is clicked? The way I checked it was there was with jprofiler.

public class MemoryTestApplication extends Application {

    @Override
    public void start(Stage primaryStage) {
        //root pane
        final VBox root = new VBox();

        //label to remove when button is clicked
        final Label label = new Label("Remove Me");
        root.getChildren().add(label);

        //button to remove label
        Button btn = new Button("Remove label");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                root.getChildren().remove(label);
            }
        });
        root.getChildren().add(btn);

        //create scene and stage
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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


推荐答案

您的事件处理程序的匿名内部类持有对标签的引用,并且您的按钮持有对事件处理程序的引用。

Your anonymous inner class for the event handler is holding a reference to the label, and your button is holding a reference to the event handler.

匿名内部类将具有由编译器创建的两个合成生成的字段,如:

The anonymous inner class is going to have two synthetically generated fields, created by the compiler, like:

final Label val$label;
final MemoryTestApplication this$0;

由于这些是最终的,因此使用后无法清除标签label = null; ,所以我认为最好的办法是将事件处理程序更改为普通的命名类,将标签引用传递给它的构造函数,然后在使用它删除之后将其清除布局中的标签。 (您可能希望在删除之前测试它不是null,因此只有在第一次按下按钮时才会删除它。)

Since these are final, you can't clear label after using it by label = null;, so I think your best bet is to change the event handler to a normal, named class, pass the label reference in to its constructor, and then clear it after using it to remove the label from the layout. (You would want to test that it was not null before removing, so that it would only be removed the first time the button is pressed).

这篇关于JavaFX GUI不释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆