Search code examples
javaimageloopstimeralternate

Alternating images with a timer using java


Since I'm not a CS major, I'm having some difficulties translating my programming wishes into an actual program. What it basically boils down to is the following: how can I alternate an image on a label, showing each image for an amount of tim specific for each image.

So: say I've images A and B; I'd like the user to see A for 1000ms and B for 200ms. This keeps on looping until a user presses a certain key.

Now, I'm able to load an image onto a panel, quite easily even, and I've managed to catch user input using KeyListener and stuff, which all works quite nicely and alot easier then I had expected. I also know how to use looping constructs like while, for and do..while, but this timer business is shady.

I see all kinds of stuff using threads and what not, I really don't need that. This is not about efficient programming or good code, it's simply about demonstrating something. Any help would be greatly appreciated!


Solution

  • Use a SwingWorker<Void, Void>. The doInBackground method of the SwingWorker should look like this :

    @Override
    protected Void doInBackground() {
        try {
            while (true) {
                displayImage(imageA);
                Thread.sleep(1000L);
                if (isCancelled()) {
                    return null;
                }
                displayImage(imageB);
                Thread.sleep(200L);
                if (isCancelled()) {
                    return null;
                }
            }
        }
        catch (InterruptedException e) {
            // ignore
        }
        return null;
    }
    
    private void displayImage(final Icon image) {
        SwingUtilituies.invokeLater(new Runnable() {
            @Override
            public void run() {
                // display the image in the panel
            }
        });
    }
    

    The keylistener should simply cancel the SwingWorker.