Page 1 of 2 12 LastLast
Results 1 to 20 of 30
Like Tree3Likes

Thread: 'sleep' not working well

  1. #1
    rng
    rng is offline Member
    Join Date
    Jan 2012
    Posts
    23
    Rep Power
    0

    Default 'sleep' not working well

    I have modified Points.java from this link: Basic drawing

    It draws small lines at random points. But I want these lines to draw after an interval of 100 msec each time. So I tried to use Thread.sleep() function, but the program just stops. Please help.

    Java Code:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Insets;
    
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    
    import java.util.Random;
    
    
    public class Points extends JPanel {
    
      public void paintComponent(Graphics g) {
          super.paintComponent(g);
    
          Graphics2D g2d = (Graphics2D) g;
    
          g2d.setColor(Color.blue);
    
          Dimension size = getSize();
          Insets insets = getInsets();
    
          int w =  size.width - insets.left - insets.right;
          int h =  size.height - insets.top - insets.bottom;
    
          Random r = new Random();
    
          for (int i=0; i<1000; i++) {
              int x = Math.abs(r.nextInt()) % w;
              int y = Math.abs(r.nextInt()) % h;
              g2d.drawLine(x, y, x+5, y+5);
              try{Thread.sleep(100); } catch(Exception e)
                  {System.out.println("Exception in sleep function..");}; 
          }
      }
    
      public static void main(String[] args) {
    
          JFrame frame = new JFrame("Points");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.add(new Points());
          frame.setSize(750, 600);
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
      }
    }
    Thanks in advance.

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is online now Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    4,039
    Rep Power
    10

    Default Re: 'sleep' not working well

    Never call Thread.sleep() from the EDT. All you're doing is causing the call to paintComponent() to take longer, which must finish before displaying anything. You're just blocking the EDT, which will cause your GUI to become unresponsive and buggy.

    Instead, create a Swing Timer that adds to some data structure that holds everything to be drawn. From paintComponent, simply draw everything in that data structure.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    rng
    rng is offline Member
    Join Date
    Jan 2012
    Posts
    23
    Rep Power
    0

    Default Re: 'sleep' not working well

    Thanks for the info. Could you please explain with some code.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: 'sleep' not working well

    Quote Originally Posted by rng View Post
    Thanks for the info. Could you please explain with some code.
    You can find great explanation about use of Swing Timers and code at the tutorials: How to use Swing Timers

  5. #5
    rng
    rng is offline Member
    Join Date
    Jan 2012
    Posts
    23
    Rep Power
    0

    Default Re: 'sleep' not working well

    I am trying to add following Timer:

    Java Code:
    javax.swing.Timer tm = new javax.swing.Timer(1500, new ActionListener() { public void actionPerformed(ActionEvent e)  { g2d.repaint();}  } ).start()  ;
    But I am getting this error:

    Java Code:
    ActionListener cannot be resolved to a type

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default Re: 'sleep' not working well

    Have you imported it?

  7. #7
    rng
    rng is offline Member
    Join Date
    Jan 2012
    Posts
    23
    Rep Power
    0

    Default Re: 'sleep' not working well

    Yes. Following is the code I am trying:
    Java Code:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Insets;
    
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.Timer; 
    
    import java.util.Random;
    
    public class Points extends JPanel {
    
      public void paintComponent(Graphics g) {
          super.paintComponent(g);
    
          Graphics2D g2d = (Graphics2D) g;
    
          g2d.setColor(Color.blue);
    
          Dimension size = getSize();
          Insets insets = getInsets();
    
          int w =  size.width - insets.left - insets.right;
          int h =  size.height - insets.top - insets.bottom;
    
          Random r = new Random();
          int i=0; 
          Timer tm = new Timer(500, new ActionListener() { public void actionPerformed(ActionEvent e)  {
              if (i>1000) return;
    	  int x = Math.abs(r.nextInt()) % w;
              int y = Math.abs(r.nextInt()) % h;
              g2d.drawLine(x, y, x+5, y+5);
              i++; 
          	  }; //end action performed;   
          } //end actionlistener; 
          ); //end timer tm; 
          tm.start(); 
      }
       
      public static void main(String[] args) {
          JFrame frame = new JFrame("Points");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.add(new Points());
          frame.setSize(750, 600);
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
      }
    }
    It gives following error:
    Java Code:
    Points.java:32: error: ActionListener cannot be resolved to a type
    	Timer tm = new Timer(500, new ActionListener() { public void actionPerformed(ActionEvent e)  {
    	                              ^^^^^^^^^^^^^^
    Last edited by rng; 01-18-2012 at 02:56 AM.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: 'sleep' not working well

    I see no import for the ActionListener type. Toll's question is still quite valid.

  9. #9
    KevinWorkman's Avatar
    KevinWorkman is online now Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    4,039
    Rep Power
    10

    Default Re: 'sleep' not working well

    On top of the advice you're already receiving, I didn't mean for you to create a new Timer every time paintComponent() is called. Create the Timer separate from the paintComponent() method, and call repaint() from it instead. In paintComponent(), simply draw whatever is in the data structure, which the Timer will add to.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  10. #10
    Bestsanchez is offline Member
    Join Date
    Jan 2012
    Location
    The Coffee Pot
    Posts
    36
    Rep Power
    0

    Default Re: 'sleep' not working well

    ActionListener is an interface so doesn't it have to be implemented to be used?


    Java Code:
    public class Points extends JPanel implements ActionListener{
        ////
        ////
        Timer tm = new Timer(500, this);
        ////
        public void actionPerformed(ActionEvent e)  {
           ////
        }
        ////
    }
    Oh and I think you need:

    Java Code:
    import java.awt.event.*;
    Last edited by Bestsanchez; 01-18-2012 at 04:48 AM.

  11. #11
    rng
    rng is offline Member
    Join Date
    Jan 2012
    Posts
    23
    Rep Power
    0

    Default Re: 'sleep' not working well

    I want a delay of 500 milliseconds between drawing of two lines. Will following work:

    Java Code:
    import java.awt.event.*; 
    
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Insets;
     
    import javax.swing.JPanel;
    import javax.swing.JFrame;
     
    import java.util.Random;
     
     
    public class Points extends JPanel implements ActionListener {
     
        Timer tm = new Timer(500, this);
        
        public void actionPerformed(ActionEvent e)  {
                repaint();  
        }
      
       public void paintComponent(Graphics g) {
          super.paintComponent(g);
     
          Graphics2D g2d = (Graphics2D) g;
     
          g2d.setColor(Color.blue);
     
          Dimension size = getSize();
          Insets insets = getInsets();
     
          int w =  size.width - insets.left - insets.right;
          int h =  size.height - insets.top - insets.bottom;
     
          Random r = new Random();
     
          for (int i=0; i<1000; i++) {
              int x = Math.abs(r.nextInt()) % w;
              int y = Math.abs(r.nextInt()) % h;
              g2d.drawLine(x, y, x+5, y+5);
          }
      }
     
      public static void main(String[] args) {
     
          JFrame frame = new JFrame("Points");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.add(new Points());
          frame.setSize(750, 600);
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
      }
    }
    I think I need to write 'tm.start();' somewhere, but I do not know where. Thanks for your help.

    'sleep(500);' used to be so simple in C!
    Last edited by rng; 01-18-2012 at 05:56 AM.

  12. #12
    Bestsanchez is offline Member
    Join Date
    Jan 2012
    Location
    The Coffee Pot
    Posts
    36
    Rep Power
    0

    Default Re: 'sleep' not working well

    A few things I notice:
    Put 'draw new line' code in 'actionPerformed'
    Put tm.start(); in the constructor...

    Oh and you'll probably need a constructor...

    Oh and you should probably construct the object itself in main.

  13. #13
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

    Default Re: 'sleep' not working well

    Quote Originally Posted by Bestsanchez View Post
    ActionListener is an interface so doesn't it have to be implemented to be used?
    Yes, but it's not necessary or even desirable to implement it in a public class. The approach already shown in this thread, which involves an anonymous inner class, is far more common and in most cases improves readability and maintainability.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  14. #14
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

    Default Re: 'sleep' not working well

    Quote Originally Posted by Bestsanchez View Post
    A few things I notice:
    Put 'draw new line' code in 'actionPerformed'
    Put tm.start(); in the constructor...

    Oh and you'll probably need a constructor...

    Oh and you should probably construct the object itself in main.
    It's nice that you want to help, but I suspect you need more experience in Java before you can make any meaningful suggestions in this topic.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  15. #15
    Bestsanchez is offline Member
    Join Date
    Jan 2012
    Location
    The Coffee Pot
    Posts
    36
    Rep Power
    0

    Default Re: 'sleep' not working well

    Quote Originally Posted by DarrylBurke View Post
    It's nice that you want to help, but I suspect you need more experience in Java before you can make any meaningful suggestions in this topic.

    db
    I'll go back to asking questions instead of answering them because you're right, i'm only 4 months into java experience haha.

  16. #16
    rng
    rng is offline Member
    Join Date
    Jan 2012
    Posts
    23
    Rep Power
    0

    Default Re: 'sleep' not working well

    I am now using following code. A line is being drawn at intervals of 500msec (some movement on screen after all!) but each time the previous line is being erased. At any time there is only one line on screen. I want lines to come one after another, without previous one being erased. Also system is exiting after 10 lines only while I have coded it to exit after drawing 20 lines.
    Java Code:
    import java.awt.event.*;
     
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Insets;
      
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.Timer; 
      
    import java.util.Random;
       
    public class Points extends JPanel implements ActionListener {
         
        public void actionPerformed(ActionEvent e)  {
                repaint(); 
        }
        
        int counter=0; 
        static Timer tm; 
       
       public void paintComponent(Graphics g) {
          tm = new Timer(500, this); 
          tm.start(); 	
          super.paintComponent(g);
      
          Graphics2D g2d = (Graphics2D) g;
      
          g2d.setColor(Color.blue);
      
          Dimension size = getSize();
          Insets insets = getInsets();
      
          int w =  size.width - insets.left - insets.right;
          int h =  size.height - insets.top - insets.bottom;
      
          Random r = new Random();
      
          int x = Math.abs(r.nextInt()) % w;
          int y = Math.abs(r.nextInt()) % h;
          g2d.drawLine(x, y, x+5, y+5);
          counter++; 
          if (counter>20) System.exit(0); 
      }
      
      public static void main(String[] args) {
          JFrame frame = new JFrame("Points");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.add(new Points());
          frame.setSize(750, 600);
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
      }
    }
    Thanks in advance.

  17. #17
    KevinWorkman's Avatar
    KevinWorkman is online now Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    4,039
    Rep Power
    10

    Default Re: 'sleep' not working well

    Like I already said- you need a data structure that holds everything to be drawn. You need a Timer (which is NOT initialized inside paintComponent) that adds to that data structure and calls repaint. Inside paintComponent, you simply draw everything in that data structure.
    Fubarable likes this.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  18. #18
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: 'sleep' not working well

    Agrees with all that Kevin has said and to amplify, the paintComponent method is for painting alone and nothing else, no program logic, no object creation, nothing. It needs to be small and fast as possible.

  19. #19
    rng
    rng is offline Member
    Join Date
    Jan 2012
    Posts
    23
    Rep Power
    0

    Default Re: 'sleep' not working well

    You need a Timer that adds to that data structure and calls repaint.
    I can't get what is meant by timer 'adds to' that data structure. Do I create Timer tm in the data structure class or in main()?

  20. #20
    KevinWorkman's Avatar
    KevinWorkman is online now Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    4,039
    Rep Power
    10

    Default Re: 'sleep' not working well

    Quote Originally Posted by rng View Post
    I can't get what is meant by timer 'adds to' that data structure. Do I create Timer tm in the data structure class or in main()?
    Huh? What would it mean to create a Timer in the data structure? And what happened when you just tried it out?
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

Page 1 of 2 12 LastLast

Similar Threads

  1. Thread.sleep
    By Gog in forum New To Java
    Replies: 3
    Last Post: 01-13-2011, 09:14 AM
  2. Do I have to put Thread to sleep?
    By atch in forum New To Java
    Replies: 0
    Last Post: 03-08-2010, 11:21 AM
  3. Sleep in thread
    By jithan in forum New To Java
    Replies: 1
    Last Post: 08-27-2008, 03:27 PM
  4. Replies: 8
    Last Post: 05-28-2008, 08:00 AM
  5. How to use the sleep and thread?
    By jiuhu in forum Java Applets
    Replies: 4
    Last Post: 08-07-2007, 03:56 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •