Results 1 to 7 of 7
  1. #1
    musico is offline Member
    Join Date
    May 2011
    Posts
    11
    Rep Power
    0

    Default Breaking out a timer loop

    I am still working on animation in java using the simple bouncing ball sprite example. Here is what I have so far.

    Java Code:
    package bouncingball;
    
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    
    public class BounceThread {
      public static void main(String[] args) {
        JFrame frame = new BounceThreadFrame();
        frame.show();
      }
    }
    
    class BounceThreadFrame extends JFrame {
      public BounceThreadFrame() {
        setSize(300, 200);
        setTitle("Bounce");
    
        addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
          }
        });
    
        Container contentPane = getContentPane();
        canvas = new JPanel();
        contentPane.add(canvas, "Center");
        JPanel p = new JPanel();
        addButton(p, "Start", new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
            Ball b = new Ball(canvas);
            b.start();
          }
        });
    
        addButton(p, "Close", new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
            canvas.setVisible(false);
            System.exit(0);
          }
        });
        contentPane.add(p, "South");
      }
    
      public void addButton(Container c, String title, ActionListener a) {
        JButton b = new JButton(title);
        c.add(b);
        b.addActionListener(a);
      }
    
      private JPanel canvas;
    }
    
    class Ball extends Thread {
      public Ball(JPanel b) {
        box = b;
      }
    
      public void draw() {
        Graphics g = box.getGraphics();
        g.fillOval(x, y, XSIZE, YSIZE);
        g.dispose();
      }
    
      public void move() {
        if (!box.isVisible())
          return;
        Graphics g = box.getGraphics();
        g.setXORMode(box.getBackground());
        g.fillOval(x, y, XSIZE, YSIZE);
        x += dx;
        y += dy;
        Dimension d = box.getSize();
        if (x < 0) {
          x = 0;
          dx = -dx;
        }
        if (x + XSIZE >= d.width) {
          x = d.width - XSIZE;
          dx = -dx;
        }
        if (y < 0) {
          y = 0;
          dy = -dy;
        }
        if (y + YSIZE >= d.height) {
          y = d.height - YSIZE;
          dy = -dy;
        }
        g.fillOval(x, y, XSIZE, YSIZE);
        g.dispose();
      }
    
      public void run() {
    	  {
    		   int delay = 15; //milliseconds
    		   draw();
    		   
    		   ActionListener taskPerformer = new ActionListener()
    		      {
    		      public void actionPerformed(ActionEvent evt)
    		         {   
    		         move();
    		         }
    		      };
    
    		   Timer test = new Timer(delay, taskPerformer);
    
    		   test.start();
    
    		   System.out.println( test.isRunning() );
    		   System.out.println( test.getDelay() );
    		   
    		   try {
    			      Thread.sleep(10000);
    			   }
    			   catch (Exception e) {}
    
    		   test.stop();
    		   System.out.println( test.isRunning() );
    
    		   }
      }
    
      private JPanel box;
      private static final int XSIZE = 10;
      private static final int YSIZE = 10;
      private int x = 0;
      private int y = 0;
      private int dx = 10;
      private int dy = 5;
    }
    At the moment it is set to run until time reaches 10 seconds (sleep(10000)), but how would I break out sooner like if a certain coordinate was reached or after a certain time period before the sleep value? I tried adding an if (condition) - test.stop() but that didn't work.
    Last edited by musico; 06-23-2011 at 07:52 PM.

  2. #2
    Jonah Bron's Avatar
    Jonah Bron is offline Member
    Join Date
    Sep 2010
    Location
    California
    Posts
    26
    Rep Power
    0

    Default

    First, please edit your post and surround the code with [ CODE][/CODE] tags to make it more readable.

    Quote Originally Posted by musico View Post
    I tried adding an if (condition) - test.stop() but that didn't work.
    Why didn't it work? Can you post it?

  3. #3
    musico is offline Member
    Join Date
    May 2011
    Posts
    11
    Rep Power
    0

    Default

    OK fixed the code tags. Thanks for pointing these out.

    The code added to the try-catch part was

    Java Code:
    try {
    			   if(x>150)
    				   test.stop();
    			      Thread.sleep(10000);
    			   }
    			   catch (Exception e) {}
    Puting the conditional statement in the actionPerformed loop itself meant it wasn't recognised as the instance test is not declared until later. No tutorial I can find deals with this, at least in a clear enough way. (Im not a beginner with Java itself but very much am with the Swing components)

  4. #4
    musico is offline Member
    Join Date
    May 2011
    Posts
    11
    Rep Power
    0

    Default

    These likns at the bottom are so useful. Got the answer from this thread
    http://www.java-forums.org/java-appl...ide-timer.html

    Unless there is an even better way but that will do just now.

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

    Default

    I;m slowly going through your code and immediately I see that you seem to be doing several things wrong including using deprecated method such as JFrame#show(). Also you shouldn't get Graphics by calling getGraphics on a component. Instead you should be doing passive drawing unless you have a very strong reason not to and know the pitfalls of doing this.

    Possibly more to come.

    More:

    You are making Swing calls from within a background thread which is very dangerous and will likely cause your program to freeze and die at unexpected times. Why use a background thread at all rather than a Swing Timer?
    Last edited by Fubarable; 06-23-2011 at 08:22 PM.

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

    Default

    Quote Originally Posted by musico View Post
    These likns at the bottom are so useful. Got the answer from this thread
    http://www.java-forums.org/java-appl...ide-timer.html

    Unless there is an even better way but that will do just now.
    That was my answer, so it must be the best way (kidding).

  7. #7
    musico is offline Member
    Join Date
    May 2011
    Posts
    11
    Rep Power
    0

    Default

    I'm obviously using the wrong tutorials. What are the best ones (apart from Oracle?)

    btw I thought this was rid of the thread hence the swing timer function there.

    Ive changed the show line to setVisible(true).

Similar Threads

  1. Stopping a Timer from Inside the timer
    By krishnan in forum Java Applets
    Replies: 2
    Last Post: 10-04-2010, 11:15 PM
  2. breaking out of while loop
    By mac in forum New To Java
    Replies: 5
    Last Post: 05-18-2010, 03:21 PM
  3. Inside a Timer thread loop,how to refresh a JTable in swing
    By neha_negi in forum Threads and Synchronization
    Replies: 3
    Last Post: 09-04-2009, 01:45 AM
  4. How to use timer to monitor lengthy loop progress
    By JotaPe in forum New To Java
    Replies: 7
    Last Post: 06-26-2009, 06:14 AM
  5. Replies: 0
    Last Post: 04-04-2008, 02:46 PM

Posting Permissions

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