yardenK
yardenK

Reputation: 312

i tried show image for 3 seconds and then switched in java gui but its doesnt work

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

Answers (1)

Don Brody
Don Brody

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

Related Questions