Andy Jin
Andy Jin

Reputation: 1

Thread.sleep not displaying image properly in paintComponent

When drawing a BufferedImage , the transition image does not display. I am trying to create a game in which when the user wins, it displays a loading transitional screen and then proceeds to the img2 screen. I want to create a 1 or 2 second delay to make it seem as though the second level is in the process of loading however when I add thread.sleep it delays it but does not display the transition image, instead, it just jumps straight toimg2. I have tried creating separate flags,methods and increasing the time but nothing seems to work!

Below is the paintComponenetmethod (I have tried separating into separate methods):

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (img != null) {
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.drawImage(img, 0, 0, this);
        if (win1 == true) {
            try {
                Thread.sleep(1000);
            } catch (Exception exc) {
            }
            g2d.drawImage(transition, 0, 0, this);
            try {
                Thread.sleep(1000);
            } catch (Exception exc) {
            }
            g2d.drawImage(img2, 0, 0, this);
        }
    }
}

An explanation would be very helpful as well!

Upvotes: 0

Views: 271

Answers (1)

camickr
camickr

Reputation: 324108

All painting is done on the Event Dispatch Thread.

When you invoke Thread.sleep() in the paintComponent() method the GUI can't repaint itself until all the code is finished executing which means only the last image will ultimately get painted as the two paint requests will be combined into one. Read the section from the Swing tutorial on Concurrency for more information.

Don't use Thread.sleep() in a painting method.

The better solution is to not even do custom painting. Instead you can just use a JLabel and change the Icon of the label.

Then you can use use a Swing Timer to schedule the animation. So you would set the Icon and then set the Timer to fire in 2 seconds. When the Timer fires you reset the Icon of the label.

Upvotes: 1

Related Questions