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);
}
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...
JLabel
(background
)img
, scaled downImageIcon
to wrap around the Image
ImageIcon
to the JLabel
JLabel
you just created to the JLayeredPane
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