I have JToggleButton and this method capturing events:
tgl_playMouseClicked(java.awt.event.MouseEvent evt) {
new Thread() {
public void run() {
int i = 0;
String outputName = null;
while ((i <= 99)) {
ImageIcon imgThisImg = new ImageIcon("images/" + outputName + i + ".png");
lbl_image.setIcon(imgThisImg);
i++;
}
tgl_play.setSelected(!tgl_play.isSelected());
}
}.start();
}
I try to simulate video by reading and showing single images in imageIcon.
When I fist time click on JToggleButton, all is ok. Video is running. But when I press again, nothing happens. The event is captured as prints are displayed in output, but no refresh on ImageIcon.
I use thread there in order to be able to set some delay between frames.
What’s wrong? Help me please
I think that one of your best shot is to use
javax.swing.Timerto pace your “video”. This will ensure that you are doing everything properly with Swing EDT.(If the millisecond is not sufficient, then I would take a look at:
java.util.concurrent.Executors.newScheduledThreadPool(int)andjava.util.concurrent.ScheduledThreadPoolExecutor.scheduleAtFixedRate(Runnable, long, long, TimeUnit)and addRunnable‘s that immediately call all their code inSwingUtilities.invokeLater())Here I made a small demo example with a list of images displaying a growing and shrinking circle (the images are created on the fly with some JPanel but this is just for the demo).