Home > Back-end >  Memory leak while scaling image as background in java swing
Memory leak while scaling image as background in java swing

Time:02-19

So, I'm trying to write a function to scale an image and use it as the background, but it allocates a lot of memory and after a few seconds the out of memory exception is raised. Here's the function that is inside an infinite loop.

public static void scale() {
        JLabel background = new JLabel();
        Image imgscale = img.getScaledInstance(back.getWidth(), back.getHeight(), Image.SCALE_SMOOTH);
        ImageIcon backgroundImage = new ImageIcon(imgscale);
        background.setIcon(backgroundImage);
        background.setSize(back.getWidth(), back.getHeight());
        jlayeredpane1.add(background, Integer.valueOf(0));
        jlayeredpane1.remove(background);
        frame.setVisible(true);
    }

CodePudding user response:

the function that is inside an infinite loop.

Wait, what!?

public static void scale() {
    JLabel background = new JLabel();
    Image imgscale = img.getScaledInstance(back.getWidth(), back.getHeight(), Image.SCALE_SMOOTH);
    ImageIcon backgroundImage = new ImageIcon(imgscale);
    background.setIcon(backgroundImage);
    background.setSize(back.getWidth(), back.getHeight());
    jlayeredpane1.add(background, Integer.valueOf(0));
    jlayeredpane1.remove(background);
    frame.setVisible(true);
}

Think about that for a second, every time this method is called you are...

  • Creating a new instance of JLabel (background)
  • Creating a new instance of img, scaled down
  • Creating a new instance of ImageIcon to wrap around the Image
  • Applying the ImageIcon to the JLabel
  • Adding the instance of the JLabel you just created to the JLayeredPane
  • Removing the instance of JLabel you just created from the JLayeredPane ... wait, what!?

And you're wondering why you're running out of memory?! I've not even mentioned the fact that this is been done within a static context.

Add in, if you're doing this within the context of the Event Dispatching Thread, you're going to cause the UI to "freeze" and if you're not doing this within the context of the Event Dispatching Thread, then you're violating the API as Swing is not thread safe.

I would suggest having a look at something like ...

some better ideas on how to achieve your goal

  • Related