Reputation: 312
I tried to make a program that shows an image for 3 seconds and then switch it but instead of showing the first image wait and then show the second image its wait show the first image and then show the second thanks for the help
JLabel image = new JLabel("");
image.setBounds(100, 20, 125, 200);
contentPane.add(image);
image.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
image.setIcon(one);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
image.setIcon(two);
}
});
Upvotes: 1
Views: 115
Reputation: 1727
Try something like this:
image.setIcon(one);
javax.swing.Timer timer = new Timer(3000, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
image.setIcon(two);
timer.stop();
}
});
Make sure to use javax.swing.Timer and not java.util.Timer since you are updating a Swing UI component. The Swing Timer executes its callback on the event dispatch thread (EDT).
With that said, consider using the SwingWorker for long running tasks (i.e. if the image files in your example are large). The docs recommend that only small/short tasks are executed with the approach above.
Upvotes: 3