Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: while loop keeps going too long

  1. #1
    Junior Member
    Join Date
    Sep 2011
    Posts
    29
    Thanks
    2
    Thanked 2 Times in 2 Posts

    Default [solved] while loop keeps going too long

    I'm trying to make a Game of Life program but something isn't working right. I have a play/pause button but after it is pressed the main loop keeps going for several iterations before it stops. The button's text changes which shows the paused variable has already changed though. I can't figure out why it keeps going like that.

    The code, I tried to take out all the non relevant bits to make it easier to read:
    (the while loop is the one in runGame() that says while(!paused), in the real code heavyLifting() is the bit that changes the cells from one iteration to the next)
    package Games;
     
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.geom.*;
     
    public class Checking
    {	
    	private JFrame frame;
    	private LPanel canvas;
    	private int elapsedtime;
    	private int timepertick;
    	private long lasttime;
    	private boolean paused;
    	private int iteration;
     
    	public Checking()
    	{
    		//constructor
    		elapsedtime = 0;
    		timepertick = 16; //milliseconds
    		iteration = 0;
    		lasttime = 0;		
    		paused = true; //start out paused				
    		createAndShowGUI();
    	}
     
    	private void createAndShowGUI()
    	{
    		frame = new JFrame("just checking");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		canvas = new LPanel(this);
    		frame.add(canvas);
    		frame.pack();
    		frame.setVisible(true);
    	}
     
    	private long getElapsedTime()
    	{
    		long thistime = System.currentTimeMillis();
    		long time = thistime - lasttime;
    		lasttime = thistime;
    		return time;
    	}
     
    	private void runGame()
    	{
    		while(true)
    		{
    			while(!paused)
    			{
    				elapsedtime = elapsedtime + (int) getElapsedTime();
    				while(elapsedtime>timepertick)
    				{								
    					heavyLifting();
    					iteration++;
    					elapsedtime = elapsedtime - timepertick;
    					canvas.repaint();					
    				}
    			}
    		}		
    	}
     
    	private void heavyLifting()
    	{
    		try
    		{
    			Thread.sleep(100);
    		}
    		catch(InterruptedException ie)
    		{
    			System.out.println("bleh");
    		}
    	}
     
    	public int getIteration()
    	{
    		return iteration;
    	}
     
    	public void togglePause()
    	{
    		if(!paused)
    		{
    			paused = true;
    		}
    		else
    		{
    			lasttime = System.currentTimeMillis();;
    			paused = false;
    		}
    	}
     
    	public boolean isPaused()
    	{
    		return paused;
    	}
     
    	public static void main(String[] args)
    	{
    		Checking c = new Checking();
    		c.runGame();
    	}
    }
     
    class LPanel extends JPanel
    {
    	private Checking ref;
    	private final Color backgroundcolour = Color.BLACK;
    	private final Color textcolour = Color.YELLOW;
    	private final int leftoffset = 200;
    	private final int topoffset = 25;
    	private Rectangle2D playbutton;
     
    	public LPanel(Checking reference)
    	{
    		//constructor
    		ref =  reference;
    		setBackground(Color.BLACK);
    		playbutton = new Rectangle2D.Double(); //just in case
     
    		addMouseListener(new MouseAdapter(){
    			public void mouseClicked(MouseEvent e){
    				receiveClick( e.getX(), e.getY() );				
    			}
    		});
     
    	}
     
    	private void receiveClick(int x, int y)
    	{
    		if( onButton(x,y) )
    		{
    			ref.togglePause();
    		}
    	}
     
    	private boolean onButton(int x, int y)
    	{
    		return playbutton.contains(x,y);
    	}
     
    	private void drawSidebar(Graphics2D g2)
    	{
    		//draw the "button"
    		int width = 150;
    		int height = 75;
    		int x = 25;
    		int y = topoffset;
    		g2.setStroke( new BasicStroke(5.0F) );
    		g2.setColor(textcolour);
    		playbutton = new Rectangle2D.Double(x,y,width,height);
    		g2.draw( playbutton );
    		String text;
    		if(ref.isPaused())
    		{
    			text = "Play";
    		}
    		else
    		{
    			text = "Pause";
    		}
    		g2.setFont( new Font("Arial", Font.PLAIN, 20) );
    		FontMetrics fm = g2.getFontMetrics();
    		int h = fm.getHeight();
    		int w = fm.stringWidth(text);
    		x = (leftoffset/2) - (w/2);
    		y = y+(height/2)+7;
    		g2.drawString(text,x,y);
     
    		text = "Iteration: " + game.getIteration();
    		w = fm.stringWidth(text);
    		x = (leftoffset/2) - (w/2);
    		y = y + height + h;
    		g2.drawString(text,x,y);
    	}
     
    	public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
    		drawSidebar(g2);
        }		
     
    	public Dimension getPreferredSize()
        {
            return new Dimension(800,600);
        }
    }
    Last edited by Harry Blargle; March 30th, 2012 at 03:23 PM.


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: while loop keeps going too long

    First, I'd recommend looking into using a SwingTimer to do your tasks. All those nested loops are could be removed with the timer, the third one in looks to be the culprit (will keep looping until complete when you pause, as the pause stops the outer loop)

  3. #3
    Junior Member
    Join Date
    Sep 2011
    Posts
    29
    Thanks
    2
    Thanked 2 Times in 2 Posts

    Default Re: while loop keeps going too long

    Ah, so obvious now that you pointed it out, thanks.

Similar Threads

  1. Bulk write of big int[] and long[]
    By nwp in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: December 4th, 2011, 03:28 PM
  2. Converting Object to Long
    By aussiemcgr in forum Java Theory & Questions
    Replies: 5
    Last Post: August 20th, 2010, 08:35 AM
  3. Sudoku Creator (this could be a long one)
    By aussiemcgr in forum Java Theory & Questions
    Replies: 8
    Last Post: July 27th, 2010, 12:19 PM
  4. How long did it take you to learn?
    By JavaLearner in forum The Cafe
    Replies: 5
    Last Post: March 24th, 2010, 04:42 PM
  5. The input line is too long
    By vivekmk in forum Java IDEs
    Replies: 5
    Last Post: October 16th, 2009, 10:35 PM