sleep thread within four loop JFrame

My progrm is a Keno like game where you choose your numbers out of a grid of JTextFields and then you click play and the computer should randomly change the textfield colors up to 20 times.

My problem

Alright so i have a sleep thread within my four loop, the sleep thread should pause whats happening within the four loop for a second and then change the textfield color every second but instead it waits like 10 seconds and displays all the random textfields that were chosen and changed there colors all at the same time.

Here is the code

	public void computerPick()
	{

		

		for(int i = 0; i < rollAmnt; i++)
		{
			
			
		
			
		SwingUtilities.invokeLater(new Runnable()
		{
			public void run()
			{
				
				try
				{
					roll = (int)(Math.random()* 79)+ 1;
					Thread.sleep(100);
					if(field[roll].getBackground() == Color.white)
					{
						field[roll].setBackground(Color.orange);
					}
					else if(field[roll].getBackground() == Color.green)
					{
						field[roll].setBackground(Color.cyan);
						win++;
					}
					else if(field[roll].getBackground() == Color.cyan)
					{
						field[roll].setBackground(Color.magenta);
						field[roll].setText("NICE!");
						win++;
					}
				}
				catch(InterruptedException aoe){}
			}
		});
		}
		
		
		
	}

please if anyone could edit this and show me what i can do to fix this i would appreciate it a ton.

In short: You only use ‘one’ thread the same thread that handles the painting EDT.

Have a look at http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html

so something like this should work:


ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
final Runnable roll = new Runnable() {
	public void run() {
		try {
			roll = (int)(Math.random()* 79)+ 1;

			if(field[roll].getBackground() == Color.white)	{
				field[roll].setBackground(Color.orange);
			} else if(field[roll].getBackground() == Color.green) {
				field[roll].setBackground(Color.cyan);
				win++;
			} else if(field[roll].getBackground() == Color.cyan)	{
				field[roll].setBackground(Color.magenta);
				field[roll].setText("NICE!");
				win++;
			}
		} catch(InterruptedException aoe){
			Thread.interrupt();
		}
	}
};
Runnable task = new Runnable() {
	public void run() {
		SwingUtilities.invokeLater(roll);
	}
}
for(int i = 1; i < rollAmnt + 1; i++)	{
   executor.schedule(task, 100 * i, TimeUnit.MILLISECONDS);
}

Though you should probably change your roll code to something else.

Oh my bad, I forgot to do invokeLater

cool thanks ill try this out and let you know if it works :slight_smile: