Alternating images with a timer using java

情到浓时终转凉″ 提交于 2019-12-24 08:52:54

问题


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!


回答1:


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.




回答2:


Here's something that might be a good example: http://www.java2s.com/Code/Java/Development-Class/UsejavautilTimertoscheduleatasktoexecuteonce5secondshavepassed.htm

I can try to explain the code if it appears confusing




回答3:


There is nothing necessarily inefficient about using threads when threads are the right tool for the job.

In this case, it would not be unreasonable to create a new class that implements Runnable, which holds a reference to the label you wish to change the image on.

This means that the image could be changed without causing waits on the main application that would cause it to hang until it was done.

You would want to avoid 'Busy Loops' [basically, a while loop with no Thread.sleep() within it], and look to see if there is any needed thread exit criteria



来源:https://stackoverflow.com/questions/5179569/alternating-images-with-a-timer-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!