javamultithreadingswingdeadlockawt-eventqueue

Java: How should I implement waiting so that Images render?


I'm not sure I've really asked the question correctly...and I'm not even sure if I've relevantly phrased the question or not..So, I apologize in advance...but I'm quite stuck on this issue and appreciate all help.. Further, I'm frankly not an expert so...please be gentle, I'm not trying to be an idiot.

So, the point of my program, frankly, is a simple game, based off of a certain game show on TV which has lifelines.. This specific one is the "phone a friend" one... I have a quote on quote 'button' (really a JPanel that has a MouseListener). Once this button is pressed, I would like it to add, and paint a JLabel or JPanel onto the JFrame, whatever works to draw an animated gif (of a countdown) and to lock the other Components until 30 seconds have occurred. For the reference, I am not using a LayoutManager at the moment...

The way I've been attempting to do this, is:

ImageIcon CountdownImg = new ImageIcon("countdown.gif");
JLabel CountdownLbl = new JLabel(CountdownImg);
this.getContentPane().add(CountdownLbl);
CountdownLbl.setLocation(200, 200);
CountdownLbl.setSize(new Dimension(CountdownImg.getIconWidth(), CountdownImg.getIconHeight()));

long startTime = System.currentTimeMillis();
while(System.currentTimeMillis() < startTime + 30000) {
    ;
}

I know the problem exists with my while loop. Without the loop, the image renders successfully. With it, java waits until after the condition is met to render CountdownLbl. I've also tried creating another JFrame with a content pane that had the image, but (probably again, due to my own misunderstanding or poor threading..) but the Frame simply appears and does not render its contents. Sometimes while running it I notice that there is a Image Fetcher thread, I'm assuming that my very bad loop could be interfering with this thread, and that this thread is what is responsible for rendering my image.

So I guess the question should be...How can I really implement this...in a thread safe way? If that is correct?

Thank you for your time, patience and effort.


Solution

  • The thread responsible for drawing the image icon is same as the thread which is executing the while loop in your case.There is something called EDT , event dispatcher thread which updates your swing UI.You are using the same EDT to wait the countdown.

    You might want to look into this SwingUtilities.invokeLater()

    EDIT:

    Should have added more information : here it is , Using SwingWorker & SwingUtilities