0

I'm making a "dice game". I'm adding JLabels to a panel with random dice images. I want them to not appear at the same time, but with a delay. I found that Thread.sleep() does the job. The problem is that when I put the sleep() inside a for-loop, the loop loops and all of the labels are repainted in the same time (after the set sleep-amount). My goal is to show the first label, sleep for an amount of time, show the next, sleep and so on. Thanks for any help!

    public void PaintLabels(Player[] players, Die[] dice, String[][] images) throws InterruptedException {
        pnlDice.removeAll(); // Remove everything from the play-area
        pnlDice.setLayout(new java.awt.GridLayout(players.length,6)); // Sets a new layout based on number of players
        JLabel[] image = new JLabel[dice.length]; // Declares an array of labels based on number of dice
        for (int i=0; i<players.length;i++) {
            for (int j=0; j<dice.length; j++) {
                image[j] = new JLabel();
                image[j].setIcon(new ImageIcon(images[i][j])); // Set the image of the label
                pnlDice.add(image[j]); // Add the label to the panel
                Thread.sleep(200);
                pnlDice.revalidate();
                pnlDice.repaint();
            }
        }
    }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • 2
    Don't call `sleep()` on the EDT but use a separate worker and add the labels in a delayed way. You're currently delaying all display updates until the last label has been added . I suggest you read up on the Event Dispatch Thread. – Thomas Sep 21 '15 at 08:12
  • 5
    [How to use Swing Timers](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html), for [example](http://stackoverflow.com/questions/28342538/java-swing-timer-and-animation-how-to-put-it-together/28342986#28342986) and [example](http://stackoverflow.com/questions/21034679/jframe-shows-up-grey-blank/21034770#21034770) – MadProgrammer Sep 21 '15 at 08:24
  • Thanks about the Timer @MadProgrammer! That did the trick. – Mattias Larsson Sep 23 '15 at 21:30

0 Answers0