4 Replies Latest reply: Sep 16, 2012 8:12 PM by 957909 RSS

    Time delay in Java

    957909
      I am trying to insert a sleeper thread inbetween two actions in an else statement, here is my code:

                     else{
                          current.setBackground(Color.red);
                          last.setBackground(Color.red);
                               try {
                                    
                                    
                                    Thread.sleep(4000);

                                    
                               } catch (InterruptedException ie)
                          {
                               System.out.println(ie.getMessage());
                               }
                          
                          
                          finally {
                          
                               last.flipBack();
                               current.flipBack();
                               last.setEnabled(true);
                               current.setEnabled(true);
                               current.setBackground(null);
                               last.setBackground(null);
                               last=null;
                     

                          
                     }
                     }

      Could someone tell me why the background changes above the try statement are being skipped, and how to fix it, or tell me of another way to put in a time delay. Thanks.
        • 1. Re: Time delay in Java
          EJP
          Sleeping in the GUI event thread is literally a waste of time, and background changes don't actually happen until the next paint event is processed, and all that your sleep is accomplishing is delaying the processing of the next paint event, and the next paint event is processing both the background changes in quick succession, probably eliminating the first one, so you don't see it.

          If you want to see the background change twice you would have to submit two SwingWorker tasks to execute several seconds apart.

          It's a GUI. Don't think sequential programming. It's not. It's event driven.
          • 2. Re: Time delay in Java
            rp0428
            >
            Could someone tell me why the background changes above the try statement are being skipped, and how to fix it, or tell me of another way to put in a time delay.
            >
            How can anyone tell execution is even getting into the ELSE half of the statement or that the actions are even part of a different thread?

            The 4 second sleep only has meaning if the actions are to objects in a different thread. If you take action in the current thread and then immediately sleep how will you see the effect of those actions?

            Post the entire code and tell us what it is you are really trying to do.
            • 3. Re: Time delay in Java
              957909
              Here is the rest of the code.

              import java.awt.Color;
              import java.awt.GridLayout;
              import java.awt.event.ActionEvent;
              import java.awt.event.ActionListener;
              import java.util.ArrayList;
              import java.util.Random;

              import javax.swing.BorderFactory;
              import javax.swing.JButton;
              import javax.swing.JFrame;
              import javax.swing.JOptionPane;

              import javax.swing.JPanel;

              public class FinalThing extends JFrame implements ActionListener{
                   static int score;
              public class Card extends JButton {
                   int Number;
                   boolean found = false;
                   boolean added = false;
                   void flipOver(){
                        this.setText(Integer.toString(Number));
                        
                   }
                   void flipBack(){
                        this.setText("?");
                   }
                   
                   public Card(int num){
                        super();
                        
                   
                        
                             Number = num;
                   }
                   }
              int size;
              JPanel panel;
              ArrayList<Card> unaddedCards;
              Card cards[][];
              Card last= null;

              public FinalThing(){
                   this.setTitle("Memory Game");
                   this.setSize(625,700);
                   size= Integer.parseInt(JOptionPane.showInputDialog("How big do you want your game to be?"));
                   if (size%2==1){
                        JOptionPane.showMessageDialog
                        (null, "Must be an even number.");
                        size= Integer.parseInt(JOptionPane.showInputDialog("How big do you want your game to be?"));
                        if (size%2==1){
                             JOptionPane.showMessageDialog
                             (null, "Goodbye");
                             System.exit(0);
                        }
                   }

                   this. init ();
                   this.setVisible(true);
                   
                   }


              void init(){
                   unaddedCards = new ArrayList<Card>();
                   Random r = new Random();
                   int count = 0;
                   while(count < size*size/2){
                        Card temp = new Card(count);
                        Card match = new Card(count);
                        unaddedCards.add(temp);
                        unaddedCards.add(match);
                        count++;
                        
                   }
              panel= new JPanel(
                        new GridLayout(size,size)
                        );
                   panel.setBorder(BorderFactory.createTitledBorder(Integer.toString(score)));
              cards= new Card[size][size];

              int i;
              int j;
              for(i=0; i<size; i++){
                   for(j= 0; j<size; j++){
                        int pick;
                        if(unaddedCards.size() > 0)
                        pick = r.nextInt(unaddedCards.size());
                        else
                             pick = 0;

                        cards[i][j] = unaddedCards.get(pick);
                        
                        unaddedCards.remove(pick);
                        
                        cards[i][j]. setText("?");
                        cards[i][j].addActionListener(this);
                        panel.add(cards[i][j]);


                   
                   }
              }



              this.add(panel);
              }






                   /**
                   * @param args
                   */
                   public static void main(String[] args) {
                   
                        // TODO Auto-generated method stub
                        
                        score=0;
                        new FinalThing();
                        
                        
                   }


                   @Override
                   public void actionPerformed(ActionEvent e) {
                        // TODO Auto-generated method stub
                        Card current = (Card) e.getSource();
                        
                        current.flipOver();
                        current.setEnabled(false);
                        
                        if(last!=null){
                             if(last.Number==current.Number){
                                  last.found=true;
                             current.found=true;
                             current.setBackground(Color.green);
                             last.setBackground(Color.green);
                             current.setEnabled(false);
                             last.setEnabled(false);
                             last=null;
                             score++;
                             panel.setBorder(BorderFactory.createTitledBorder(Integer.toString(score)));
                        }

                             else{
              current.setBackground(Color.red);
              last.setBackground(Color.red);
              try {


              Thread.sleep(4000);



              } catch (InterruptedException ie)
              {
              System.out.println(ie.getMessage());
              }



              finally {


              last.flipBack();
              current.flipBack();
              last.setEnabled(true);
              current.setEnabled(true);
              current.setBackground(null);
              last.setBackground(null);
              last=null;




              }
              }

              }
                             else{
                                  last=current;
                             }
                        if (score==size*size/2){
                             JOptionPane.showMessageDialog
                             (null, "You Win!!");
                             System.exit(0);
                             
                        }

                        
                   }

              }
              • 4. Re: Time delay in Java
                EJP
                There's not much point in posting more code that still has the same conceptual flaw I wrote about three weeks ago.