【问题标题】:JavaFX ImageView - Image cleanupJavaFX ImageView - 图像清理
【发布时间】:2016-07-23 06:47:53
【问题描述】:

我想问是否有人知道 JavaFX ImageView 如何处理图像清理。 当图像对象/内存空闲时。

这是给我带来问题的情况: 我的场景中有两个“标签”位置。这是我完成的选项卡:父窗格中的按钮和切换窗格。每个选项卡都有自己的 ImageView。在切换窗格之前,我将旧 ImageView 上的 Image 设为空,然后加载新的。我原以为在切换标签后,旧 ImageView 中的旧图像会免费,但实际上并非如此。

为了监控行为,我使用了 Java VisualVM 工具,并从中触发了 GC。我还通过 HeapDump 验证了对象列表,我可以在 imageview 上调用 setImage(null) 后确认该事件,旧图像仍保留在 ImageView 中,无法被 GC 收集。

如果有人能建议我如何触发 ImageView 以清除旧图像以节省内存,我将不胜感激。

以下是显示此问题的代码:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;


public class IVTestApp extends Application {

    private String img1 = "http://formaciononline.co/wp-content/uploads/2014/05/aprender-a-programar-en-Java.jpg";
    private String img2 = "https://madushan1995.files.wordpress.com/2015/02/java-institute-new-final.png";

    @Override
    public void start(Stage primaryStage) throws Exception {
        BorderPane bp = new BorderPane();

        BorderPane p1 = new BorderPane();
        ImageView iv1 = new ImageView();
        iv1.setPreserveRatio(true);
        iv1.setFitHeight(200);
        iv1.setFitWidth(300);
        p1.setCenter(iv1);

        BorderPane p2 = new BorderPane();
        ImageView iv2 = new ImageView();
        iv2.setPreserveRatio(true);
        iv2.setFitHeight(200);
        iv2.setFitWidth(300);
        p2.setCenter(iv2);

        Button tab1 = new Button("tab1");
        Button tab2 = new Button("tab2");

        tab1.setOnAction(e -> {
            iv2.setImage(null);
            iv1.setImage(new Image(img1));
            bp.setCenter(p1);
        });

        tab2.setOnAction(e -> {
            iv1.setImage(null);
            iv2.setImage(new Image(img2));
            bp.setCenter(p2);
        });

        bp.setLeft(new VBox(tab1, tab2));

        Scene scen = new Scene(bp);
        primaryStage.setScene(scen);
        primaryStage.setWidth(600);
        primaryStage.setHeight(400);
        primaryStage.show();
    }

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

}

// 注意: 我的环境包括:Windows 7 x64bit with Java x86 jdk8u40

【问题讨论】:

    标签: java image javafx


    【解决方案1】:

    您可以尝试使用“空图像”(例如,具有所需大小的 100% 透明图像 - 易于使用 Alpha 通道)而不是空值。这应该会替换内存中保存的图像,从而使其可被垃圾回收。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-12
      • 1970-01-01
      • 1970-01-01
      • 2016-08-29
      • 2014-05-09
      • 2018-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多