Jump to content

Can't refresh JLabel

- - - - -

  • Please log in to reply
3 replies to this topic

#1
agnl666

agnl666

    Programmer

  • Members
  • PipPipPipPip
  • 173 posts
  • Programming Language:C, Java, C++
  • Learning:Python, Assembly
Hi and thank you in advance for any help given. I am working on a timer program as a exercise in GUI's and I can't get it to count properly. I want to get it run right and then I will change the GUI around and make it look good.


import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.io.*;


public class Prtimer implements ActionListener

{

	

	JPanel panel;

	JFrame frame;

	JButton start;

	JButton stop;

	JLabel time;

	

	public Prtimer()

	{

		// window objects

		frame = new JFrame("TIMER!");

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		

		panel = new JPanel();

		panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));

		

		time = new JLabel("00:00");

		panel.add(time);

		

		start = new JButton("Start");

		start.add(Box.createRigidArea(new Dimension(100, 100)));

		panel.add(start);

		start.setActionCommand("Start");

    	start.addActionListener(this);

		

		stop = new JButton("Stop");

		stop.add(Box.createRigidArea(new Dimension(100, 100)));

		panel.add(stop);

		stop.setActionCommand("Stop");

    	stop.addActionListener(this);

		

		frame.setContentPane(panel);

		frame.pack();

		frame.setVisible(true);

		frame.setResizable(false);

	}

	

	public void count(boolean go)

	{

		int min = 0;

		int sec = 0;

		

		while (go)

		{

			try 

			{

				Thread.sleep(1000);

			}

			catch (InterruptedException e)

			{

			

			}

			

			sec++;

			 

			if (sec == 60) 

			{

				min++;

				sec = 0;

			}

			panel.remove(time);

			time.setText(min + ":" + sec);

			panel.add(time);

		}	

	}


	public void actionPerformed(ActionEvent ev) 

	{

    	String click = ev.getActionCommand();


		if (click == "Start") 

		{

			count(true);

		}

		if (click == "Stop") 

		{

		   count(false);		

		}

	}

	

	public static void main(String [] args)

	{

		javax.swing.SwingUtilities.invokeLater(new Runnable() 

		{

    			public void run() 

    			{

    				JFrame.setDefaultLookAndFeelDecorated(false);

    				Prtimer Screen = new Prtimer();

    			}

    	});

	}

}


The main source of error is my count method and I was hoping someone would be able to tell me what might be going wrong.

Thank You!

#2
eafkuor

eafkuor

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 218 posts
You were doing everything wrong :D
Here's a correct version, study it!

import java.awt.Dimension;

import java.awt.event.*;

import java.util.TimerTask;

import java.util.Timer;

import javax.swing.*;


public class Prtimer implements ActionListener

{

	

	private JPanel panel;

	private JFrame frame;

	private JButton start, stop;

	private JLabel time;

	

	int min=0, sec=0;

	

	private Timer timer;

	

	private class CoutTimerTask extends TimerTask{


		public void run() {

			sec++;

			 

			if (sec == 60) 

			{

				min++;

				sec = 0;

			}

			time.setText(((min<10)?"0"+min:min) + ":" + ((sec<10)?"0"+sec:sec));

			

			timer.schedule(new CoutTimerTask(), 1000);

		}

		

		

	}

	

	public Prtimer()

	{

		// window objects

		frame = new JFrame("TIMER!");

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		

		panel = new JPanel();

		panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));

		

		time = new JLabel("00:00");

		panel.add(time);

		

		start = new JButton("Start");

		start.add(Box.createRigidArea(new Dimension(100, 100)));

		panel.add(start);

		start.setActionCommand("Start");

    	start.addActionListener(this);

		

		stop = new JButton("Stop");

		stop.add(Box.createRigidArea(new Dimension(100, 100)));

		panel.add(stop);

		stop.setActionCommand("Stop");

    	stop.addActionListener(this);

		

		frame.setContentPane(panel);

		frame.pack();

		frame.setVisible(true);

		frame.setResizable(false);

	}

	

	public void actionPerformed(ActionEvent ev) {

    	String click = ev.getActionCommand();


		if (click == "Start") {

			if(timer!=null)

				timer.cancel();

			

			timer = new Timer();

			timer.schedule(new CoutTimerTask(), 1000);

		} else if (click == "Stop" && timer!=null) {

			min=sec=0;

		    time.setText("00:00");

		    timer.cancel();

		}

	}

	

	public static void main(String [] args){

		new Prtimer();

	}

}


#3
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
I think it would make more sence to use the scheduleAtFixedRate() method from the Timer class, instead of creating a new task in the previous task. It will result in the same effec tho.

About your code agnl666. The main thing you must know, is that the run method won't repeat itself. When the end of the run method is reached, the thread dies and stops.
You either want something with the Timer class as mentioned above, or you can create a thread with a while(true) and a Thread.sleep(1000) inside.
A timer is preferred in this case because it's easier to start and stop.

This is the solution closest to your given code:

/*

 * To change this template, choose Tools | Templates

 * and open the template in the editor.

 */

package jtabbedpaneTest;


import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.io.*;


public class Prtimer implements ActionListener {


    JPanel panel;

    JFrame frame;

    JButton start;

    JButton stop;

    JLabel time;

[COLOR="#ff8c00"][B]    boolean go;

    int min = 0;

    int sec = 0;[/B][/COLOR]


    public Prtimer() {

        // window objects

        frame = new JFrame("TIMER!");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        panel = new JPanel();

        panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));


        time = new JLabel("00:00");

        panel.add(time);


        start = new JButton("Start");

        start.add(Box.createRigidArea(new Dimension(100, 100)));

        panel.add(start);

        start.setActionCommand("Start");

        start.addActionListener(this);


        stop = new JButton("Stop");

        stop.add(Box.createRigidArea(new Dimension(100, 100)));

        panel.add(stop);

        stop.setActionCommand("Stop");

        stop.addActionListener(this);


        frame.setContentPane(panel);

        frame.pack();

        frame.setVisible(true);

        frame.setResizable(false);

    }


    public void count() {  

        [COLOR="#ff8c00"][B]//move these declarations to the top[/B][/COLOR]

        while (go) {

            try {

                Thread.sleep(1000);

            } catch (InterruptedException e) {

            }


            sec++;


            if (sec == 60) {

                min++;

                sec = 0;

            }            

            [COLOR="#ff8c00"][B]time.setText(min + ":" + sec);      [/B][/COLOR]      

        }

    }


    public void actionPerformed(ActionEvent ev) {

        String click = ev.getActionCommand();


        if (click == "Start") {

            [B][COLOR="#ff8c00"]if (!go) {  //otherwise 2 threads may be started and timer goes twice as fast.

                go=true;

                (new Thread(new Runnable() {

                    public void run() {

                        count();

                    }

                })).start();[/COLOR][/B]

            }

        }

        if (click == "Stop") {

            [COLOR="#ff8c00"][B]go = false;[/B][/COLOR]

        }

    }


    public static void main(String[] args) {

        [COLOR="#ff8c00"][B]//doesn't has to be invokelater here[/B][/COLOR]

                JFrame.setDefaultLookAndFeelDecorated(false);

                Prtimer Screen = new Prtimer();

           

    }

}



You may want to consider to move the thread.sleep to the end of the while loop, rather than the start.
It's somewhat weird when you click stop, it may still count up 1 more time.. Go and test.

#4
agnl666

agnl666

    Programmer

  • Members
  • PipPipPipPip
  • 173 posts
  • Programming Language:C, Java, C++
  • Learning:Python, Assembly
Thank you. I wanted to try to do this with out using the Timer class or creating a Timer object though I appreciate this and intend to look through it all several times.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users