Timer progressivo

7 respostas
A

Bom dia, Estou precisando de uma ajuda ! Quero criar um cronometro ou um timer progressivo, que seja iniciado e paradao pela uma variável. Por exemplo: Tenho uma variável boolean, quando ela for true inicia o cronônetro e aparacere para o usuário num jLabel, depois de iniciado o cronômetro, quando a mesma variável boolean se tornar false, o cronômetro tem que parar e mostrar o tempo do cronômetro que parou no jLabel. Fiz um método que constroi o cronômetro e aparece no jLabel, mas não consigo pará-lo.

public void iniciaCronometro(final JLabel JLProtocolo, final boolean inicia) {
        final Timer timer = new Timer();

        TimerTask tarefa = new TimerTask() {

            int hora = 0;
            int minuto = 0;
            int segundo = 0;

            public void run() {
                try {
                    if(inicia==true)
                        {
                        JLProtocolo.setText(hora + ":" + minuto + ":" + segundo);
                        segundo++;
                        if (segundo == 59) {
                            segundo = 0;
                            minuto++;
                            if (minuto == 59) {
                                minuto = 0;
                                hora++;
                                if (hora == 23) {
                                    hora = 0;
                                }
                            }
                        }
                    }
                    else
                        {
                        if(inicia==false)
                            {
                            timer.cancel();                            
                            }
                        }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        timer.schedule(tarefa, 1000,1000);

    }

7 Respostas

M

Que tal em thread?

E

Coloca o Timer como variável global.

Outra coisa:

para incrementar os minutos você deve testar

if(segundos == 60) e não 59.

Abraços

G

Variável global em Java???
Não seria “static” ??

A

Fiz de outra forma, só que agora não inicia o cronometro. Aonde estou errando ? Se puderem me dar um exemplo. Obrigado !

public void cronometro(final JLabel label, boolean inicia) {          
      
        Thread t = new Thread() { 
        int hora = 0;
        int minuto = 0;
        int segundo = 0;
  
        @Override   
        public void run() {   
  
            label.setText(hora + ":" + minuto + ":" + segundo);
                        segundo++;
                        if (segundo == 60) {
                            segundo = 0;
                            minuto++;
                            if (minuto == 60) {
                                minuto = 0;
                                hora++;
                                if (hora == 60) {
                                    hora = 0;
                                }
                            }
                        } 
                try {   
                    Thread.sleep(1000);   
                } catch (InterruptedException ex) {   
                    Logger.getLogger(ServPing.class.getName()).log(Level.SEVERE, null, ex);   
                }   
            }
    };  
        
        if(inicia==true)
            {
             t.start(); 
            }
            else
                {
                if(inicia==false)
                    {
                    t.stop();    
                    }
                {
            }            
        }     
    }
L

Oi,

Cade o looping dessa Thread?

Tchauzin!

E
alexwebsp:
Fiz de outra forma, só que agora não inicia o cronometro. Aonde estou errando ? Se puderem me dar um exemplo. Obrigado !
public void cronometro(final JLabel label, boolean inicia) {          
      
        Thread t = new Thread() { 
        int hora = 0;
        int minuto = 0;
        int segundo = 0;
  
        @Override   
        public void run() {   
  
            label.setText(hora + ":" + minuto + ":" + segundo);
                        segundo++;
                        if (segundo == 60) {
                            segundo = 0;
                            minuto++;
                            if (minuto == 60) {
                                minuto = 0;
                                hora++;
                                if (hora == 60) {
                                    hora = 0;
                                }
                            }
                        } 
                try {   
                    Thread.sleep(1000);   
                } catch (InterruptedException ex) {   
                    Logger.getLogger(ServPing.class.getName()).log(Level.SEVERE, null, ex);   
                }   
            }
    };  
        
        if(inicia==true)
            {
             t.start(); 
            }
            else
                {
                if(inicia==false)
                    {
                    t.stop();    
                    }
                {
            }            
        }     
    }
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Cronometro extends JFrame {

	private static final long serialVersionUID = 1L;

	private JLabel label;
	private JButton startButton;
	private JButton pauseButton;

	private JPanel panel;

	private int secondsTotal = 0;
	private int seconds = 0;
	private int minuts = 0;
	private int hours = 0;
	private boolean paused = true;

	private Timer timer;
	private TimerTask task;

	public Cronometro() {
		super("Cronômetro");

		initForm();
		pack();
		setVisible(true);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	private void initForm() {
		initComponents();

		panel.add(startButton, BorderLayout.WEST);
		panel.add(pauseButton, BorderLayout.CENTER);
		panel.add(label, BorderLayout.EAST);

		add(panel);

	}

	private void initComponents() {
		label = new JLabel("00:00:00");
		startButton = new JButton("Start");
		startButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				paused = false;
				updateCrono();
			}
		});
		pauseButton = new JButton("Pause");
		pauseButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				paused = true;

			}
		});

		panel = new JPanel(new BorderLayout());

		timer = new Timer();
		task = new TimerTask() {

			@Override
			public void run() {
				updateCrono();
			}
		};

		timer.schedule(task, 1000, 1000);

	}

	private void updateCrono() {
		if (!paused) {

			secondsTotal++;

			seconds = secondsTotal % 60;

			if (seconds == 0) {
				minuts++;
			}
			if (minuts == 60) {
				minuts = 0;
				hours++;
			}

			hours = hours % 24;

			String labelText = hours + ":" + minuts + ":" + seconds;
			label.setText(labelText);

		}
	}

	public static void main(String[] args) {
		new Cronometro();

	}

}
E

Comente a linha 60, onde tem:

updateCrono();
Criado 9 de agosto de 2012
Ultima resposta 9 de ago. de 2012
Respostas 7
Participantes 5