This site requires JavaScript, please enable it in your browser!
Greenfoot back
no_name
no_name wrote ...

2025/7/11

Am I cooked

no_name no_name

2025/7/11

#
this thing keeps showing up in greenfoot and its to reset the greenfoot thing when the UI rendering is having loading issues. it keeps showing up and i can't load in my game. here is the image link for what ever is happening https://ibb.co/GvT3ZRQf. And this also pops up with it, shows the errors or something. https://ibb.co/1GQBKW7V
Comwp Comwp

2025/8/19

#
Hey no_name, this is a pretty complicated problem but the answer is pretty straightforward. When Greenfoot resets your world instance, it recycles the JVM (Java Virtual Machine) which can annoyingly have some leftover data from previous runs. The most common way you will run out of heap space is by loading too many images. Even after an image is not attached to a Greenfoot Actor anymore (i.e. usually when the actor is removed from the world) its image is Cached by greenfoot so long as you used the method:
Greenfoot.loadImage(yourImage.png);
Now, there are ways to load images without them being cached. I'll put my approach here. Make a new class and put this in it:
import greenfoot.GreenfootImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

public class ImageLoader {
    public static GreenfootImage loadImageFresh(String path) {
        try {
            BufferedImage raw = ImageIO.read(ImageLoader.class.getClassLoader().getResourceAsStream("images/"+path));
            GreenfootImage img = new GreenfootImage(raw.getWidth(), raw.getHeight());
            img.getAwtImage().getGraphics().drawImage(raw, 0, 0, null);
            return img;
        } catch (IOException | NullPointerException e) {
            System.err.println("Failed to load image: " + path);
            return new GreenfootImage(1, 1); 
        }
    }
}
With the above block of code, you can then load an image from any class at any time by simply calling:
this.setImage(ImageLoader.loadImageFresh("myImageName.png"));
And to remove extra data from the cache, you can call Garbage Collection, which is designed to free up heap space, but will not completely clear it:
System.gc();
If you have an Act() method in your MyWorld class, you can put this in it to monitor the heap size during gameplay.
long used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if((used / (1024*1024)>100)) //100 is the number of megabytes you want to trigger gc at by default here.
{
    System.gc();
}
showText("Heap used: " + (used / (1024*1024)) + " MB", 200, 200);
You need to login to post a reply.