如何在 Java 中存储 ImageIcon

How to store ImageIcon in Java

我在 JPanel 中有一个 JButton 的矩阵 n*n。目前,我在随时间变化的每个 JButton 中设置 ImageIcon。这不是一个简单的 ImageIcon,它是我与此函数重叠的 2 个图像:

public ImageIcon DoubleImage(BufferedImage eau, BufferedImage img){
        // Create a new image.
        finalIcon = new BufferedImage(
            eau.getWidth(), eau.getHeight(),
            BufferedImage.TYPE_INT_ARGB); // start transparent

        // Get the graphics object. This is like the canvas you draw on.
        Graphics g = finalIcon.getGraphics();

        // Now we draw the images.
        g.drawImage((Image) eau, 0, 0, null); // start at (0, 0)

        img = resize((BufferedImage) img, eau.getWidth(), eau.getHeight());
        g.drawImage((Image) img, eau.getWidth()/2-img.getHeight()/2, eau.getHeight()/2-img.getWidth()/2, null); // start at (10, 10)


        // Once we're done drawing on the Graphics object, we should
        // call dispose() on it to free up memory.
        g.dispose();

        // Finally, convert to ImageIcon and apply.
        ImageIcon icon = new ImageIcon(finalIcon);

        return icon;
    }

我现在的问题是,在每次迭代时,我都必须更改 JButtons 中的图标。这意味着我必须重新绘制图标,而我没有超过 10 个不同的最终图像。但是它花费了太多时间(应用程序滞后于一个小的 10*10 矩阵;因为迭代每 1 秒发生一次,我必须解决这个问题)。我有想法在开始时创建所有图像并将它们存储在某个地方,但我真的不知道如何执行此操作?也许用枚举?就在我的 class?

的构造函数中

我必须准确地说,我的主要 class 扩展了 JButton,并且我为我的最终矩阵实例化了它的 n*n。

编辑:函数代码 resize

public static BufferedImage resize(BufferedImage img, int newW, int newH) {
        Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
        BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);

        Graphics2D g2d = dimg.createGraphics();
        g2d.drawImage(tmp, 0, 0, null);
        g2d.dispose();

        return dimg;
    }

EDIT2:我在每次迭代时执行的代码

public void iteration(){
        final Vue vue = marreGraphique.lireVue();
        final Presenter presenter = vue.lirePresenter();


        try{ //here I'm just instantiating my BufferedImage 
            eau = ImageIO.read(new File("Icones/mosaique.jpg"));
            if(grenouille){
                img = ImageIO.read(new File(presenter.getGrenouilleImg()));
            }
            else{
                img = ImageIO.read(new File(presenter.getImg(ligne, colonne)));
            }
        }
        catch (IOException e){}

        icon = DoubleImage(eau,img);

        setIcon(icon);

        setHorizontalAlignment(SwingConstants.CENTER);
        setVerticalAlignment(SwingConstants.CENTER);
    }

您可以将图像放在静态的外部 class(我们暂时称之为 Testing):

public class Testing {
    private static List<ImageIcon> images = new ArrayList<>();

    public static void add(ImageIcon im) {
        images.add(im);
    }

    public static List<ImageIcon> get() {
        return Testing.images;
    }
    public static void clear(){
        images.clear();
    }
...

然后:

icon = DoubleImage(eau,img);
Testing.add(icon);
setIcon(icon);

...

每次需要重新创建图标时,使用 Testing.clear() 清除列表。