【问题标题】:How to decrease ImageIcon double array execution time in Java如何减少 Java 中的 ImageIcon 双数组执行时间
【发布时间】:2020-04-22 09:53:18
【问题描述】:

我有一个类,它创建一个双文件数组,给定一个指定每个文件夹名称的字符串数组。然后这些文件用于创建 ImageIcons 的双数组,每个图像文件一个。带有 ImageIcons 之一的 JLabel 被添加到 JPanel 中,该 JPanel 被添加到 JFrame 中,但这大约需要 5 秒钟。如何减少此执行时间?

class Test extends JFrame
{    
    public static void main (String [] args) {
        String [] issues = {"economic", "social", "immigration"};
        Test test = new Test(issues);
    }

    public Test (String [] issues) {
        File [][] files = getFiles(issues);
        ImageIcon [][] icons = getIconArrays(files);
        getPanel(icons);

        setVisible(true);
        setSize(700, 300);
        setLocation(550, 100);
        setDefaultCloseOperation(EXIT_ON_CLOSE); 
    }

    public File [][] getFiles(String [] issues){
        File [][] files = new File[issues.length][];
        for (int i=0;i<files.length;i++) {
            File folder = new File("/Users/hecto/Documents/BlueJ Projects/politic/questions/" +
            issues[i] + "/");
            files[i] = folder.listFiles();
        }
        return files;
    }

    public ImageIcon [][] getIconArrays(File [][] files){
        ImageIcon [][] icons = new ImageIcon[files.length][files[0].length];
        for(int i=0;i<files.length;i++){
            for(int j=0;j<files[i].length;j++){
                icons[i][j] = new ImageIcon(files[i][j].toString());
                icons[i][j] = new ImageIcon
                (icons[i][j].getImage().getScaledInstance(150, 150, java.awt.Image.SCALE_SMOOTH));
            }
        }
        return icons;
    }

    public void getPanel(ImageIcon [][] icons){
        JPanel picPanel = new JPanel(new FlowLayout());
        JLabel label = new JLabel(icons[0][0]); //initially set to first image
        picPanel.add(label);
        add(picPanel);
    }
}

我确定问题在于 ImageIcon 双数组的创建。

【问题讨论】:

  • 如果您运行任何现有的图片库应用程序,您会注意到它会在后台加载图片,而不是尝试提前全部加载。这包括 Microsoft Windows“Explorer”桌面外壳。
  • 为什么要缩放图像为什么不设置图像视图以适应图像。
  • 您还将图像加载到数组中,然后用缩放版本覆盖它。
  • @mavriksc 图片大小不一,有些很大。是的,这就是我正在做的事情。
  • 预计算并存储缩略图。

标签: java swing file imageicon execution-time


【解决方案1】:

1) 您可以使用 SCALE_FAST 而不是 SCALE_SMOOTH,这取决于图像的数量,它会显着提高加载时间。

2) 使用并行化(例如,使用 ExecutorService)。

没有更多的选择,图像加载需要时间(当然你可以使用不同的图像比例、格式等,但我认为这很明显)。 在初始化 Swing 时在后台加载它们(也可以并行化)。

【讨论】:

  • 这会减少很少的执行时间。我选择调整图像大小。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-18
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 2017-03-03
  • 2012-12-31
相关资源
最近更新 更多