简体   繁体   中英

Change of pictures in JLabel

First of all, I'll show the code and then say where the problem is :

I have a class that extends JFrame. In it's constructor there is a fragment that allows to load an image into JLabel :

    try
    {
        repaint = ImageIO.read(new File(ReturnPageName(0)));
    }catch (IOException e) {
    }
    image = new ImageIcon(repaint);
    imageLabel = new JLabel();
    imageLabel.setIcon(image);
    imageLabel.setVisible(true);
    add(imageLabel);
    setUndecorated(true);
    setVisible(true);
    setSize(1024, 600);

After pressing certain button such code should be processed :

SetMenuImage(1);
 try {
    Thread.sleep(10000);
 } catch (InterruptedException e) {
    e.printStackTrace();
    }
SetMenuImage(2);

Where the function looks like that :

public void SetMenuImage(int number)
{
 try
    {
        repaint = ImageIO.read(new File(ReturnPageName(number)));
    }catch (IOException e) {
    }
    Graphics g = repaint.createGraphics();
    g.setFont(font);
    g.setColor(black);

    image = new ImageIcon(repaint);
    imageLabel.setIcon(image);
    revalidate();
    repaint();
}

There problem is that only the second image is loaded ('2'). The program goes into both functions but only the second one changes the JLabel. If I replace them ('2' goes first, then followed by '1') then '1' is shown. What might be the cause of such problem and how to overcome it ?

Thanks in advance for Your help :)

This is because you are freezing the main thread during that duration. If you read this you will see that:

repaint() does not invoke paint() directly. It schedules a call to an intermediate method, update(). Finally, update() calls paint() (unless you override update).

repaint() is asynchronous so it does not necessarily repaint the screen (ie call the paint() method) before you call sleep() . Therefore. when you freeze the main thread, you freeze the gui, and the gui is not repainted. Instead, use javax.swing.Timer (not to be confused with java.util.Timer).

See here for usage.


UPDATE:

It appears you have solved your issue already following this tutorial . Just putting it here for the benefit of future readers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM