I am trying to display an Image using applet. Image is updated after every 4 seconds so i want my applet to show updated image.I am not sure where
i should load the image i have tried to load it in the init() method as well as in "start" method but it didnt workd out for me.Can anybody please help me with this

Dani AI

Generated

A simple, reliable pattern is to treat the image refresh as a background task and make sure you actually fetch a fresh copy (rather than relying on whatever the Toolkit/browser cache is holding). The workaround shown later in this thread can make a stale image appear to update on some systems, but it is brittle. A robust approach:

  • Load the image off the Event Dispatch Thread (start a thread in start() and stop it in stop()).
  • Fetch the image with caching disabled (either add a cache-busting query string or open a URLConnection with setUseCaches(false) and read via ImageIO).
  • Replace the applet image reference and call repaint() when the new image is ready.
  • Avoid flicker by double-buffering or overriding update() to call paint().

Example (concept only — not the workaround posted by ):

private BufferedImage loadFreshImage(String name) throws IOException {
    URL url = new URL(getCodeBase(), name + "?_=" + System.currentTimeMillis());
    URLConnection conn = url.openConnection();
    conn.setUseCaches(false);
    try (InputStream in = conn.getInputStream()) {
        return ImageIO.read(in);
    }
}

Example refresh loop:

public void run() {
    while (running) {
        currentImage = loadFreshImage("graph.png");
        repaint();
        Thread.sleep(4000);
    }
}

Draw using an offscreen BufferedImage (or at least override update(Graphics g) to call paint(g)), so the screen does not flash while the image is replaced.

Troubleshooting tips: verify the server actually serves a new file (open the image URL in a browser), check HTTP cache headers, and call image.flush() before discarding an old Image if you must reuse the same object reference. Avoid relying on forced GC or short sleeps as a fix; they mask the underlying caching/drawing issues. Note that Java applets are deprecated in modern browsers — consider migrating if long-term support is required.

Hi , I added the follwing code in my applet and it solved my problem

try{ 
    // Step 1: get a Runtime object 
    Runtime r = Runtime.getRuntime(); 
    r.gc(); 
    Thread.sleep(1);

    }catch(InterruptedException xx){ xx.getMessage(); };


}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.