0

I am coding a game in java. I have two jtextFields named dice and dicecom. I want such that when I press a jButton first a random value between 1 to 6 will be shown on dice, then there shall be some time gap of about 2 seconds after which a random value between 1 to 6 will be shown on dicecom. I wrote this code:

   private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {    
    Random rand = new Random();
    int a = rand.nextInt(6);
    a++;
    dice.setText(String.valueOf(a)); 
    try
    {
    Thread.sleep(2000);
    }
    catch(InterruptedException ex)
    {
    Thread.currentThread().interrupt();
    }
    int b = rand.nextInt(6);
    b++;
    dicecom.setText(String.valueOf(b));}

But what happens is that when I press the jButton there is a two second pause in the program execution, then both values are displayed together. How do I correct my code to get the desired result?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 2
    How to use Swing Timers: https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html Study the entire Oracle tutorial for Swing. – Gilbert Le Blanc Jun 19 '20 at 11:39
  • See my answer to the question, [How to control timings of rolling two dice](https://stackoverflow.com/questions/64092425/how-to-control-timings-of-rolling-two-dice/64093526#64093526) – Gilbert Le Blanc Nov 04 '20 at 07:26

0 Answers0