DUVIDA TEMPO (nao sei implementar)

Ola galera bom to tentando implementar um programa onde quando eu clicar no botao ok ele começar a contar tempo do 0 e quando eu clicar de novo no ok ele parar a contagem e me mostrar o tempo, tem como vcs me ajudarem? não sei nem por onde começar.

Cara, uma coisa que pode funcionar é vc pegar o tempo atual (T1) do primeiro clique, e depois do segundo (T2), aí você faz:

T2 - T1

isso te dá a diferençade tempo.

Você tem três formas de fazer isso:

  1. Usando threads diretamente;
  2. Usando o java.util.timer;
  3. Usando o javax.swing.timer.

Há um exemplo de um relógio, usando os três, aqui:
http://www.guj.com.br/posts/list/52964.java#279083

Veja esse post e os dois da página 2, logo depois dele.

Espero que te ajude, não sei se é exatamente isso que você precisa e não está nas melhores praticas pois o tempo está curtu aqui, mais de qualquer forma da uma olhada.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TesteTimer.java
 *
 * Created on 15/10/2009, 11:57:26
 */

package implementacao;

import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JOptionPane;

/**
 *
 * @author jgavazzi
 */
public class TesteTimer extends javax.swing.JFrame {

    private Timer timer;

    private static final int INICIO = 0;
    private static final int DELAY_MILLISEGUNDOS = 1000;

    public TesteTimer()
    {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        labelTempo = new javax.swing.JLabel();
        buttonOk = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        labelTempo.setText("0");

        buttonOk.setText("OK");
        buttonOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonOkActionPerformed(evt);
            }
        });

        jLabel1.setText("Segundos");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(buttonOk, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(labelTempo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel1)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelTempo)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonOk)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void buttonOkActionPerformed(java.awt.event.ActionEvent evt)                                         
    {                                             
        if(timer == null)
        {
            timer = new Timer();
            timer.schedule(new Tempo(), INICIO, DELAY_MILLISEGUNDOS);
        }
        else
        {
            timer.cancel();
            JOptionPane.showMessageDialog(null, String.format("Durou: %s segundos.", labelTempo.getText()));
        }
    }                                        

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TesteTimer().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton buttonOk;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel labelTempo;
    // End of variables declaration                   

    private class Tempo extends TimerTask
    {
        public void run()
        {
            int segundos = Integer.parseInt(labelTempo.getText());

            labelTempo.setText(String.valueOf(segundos + 1));
        }
    }
}

o galera vlw pela ajuda to olhando os exemplos de vcs, porem eu queria fazer algo bem simples tem como usar JOptionPane pra fazer isso? Sem usar JPanel ou JButton?

vlw ae galera

alguem galera?

Veja se isso ajuda … =)

import java.util.TimerTask;
import javax.swing.JOptionPane;

public class Timer
{
    private int segundos;
    private java.util.Timer timer;

    public Timer()
    {
        segundos = 0;
        timer = new java.util.Timer();
    }

    public void iniciar()
    {
        timer.schedule(new Tempo(), 0, 1000);
    }

    public int getSegundos()
    {
        return segundos;
    }

    private class Tempo extends TimerTask
    {
        public void run()
        {
            segundos++;
        }
    }

    public static void main(String[] args)
    {
        Timer timer = new Timer();

        timer.iniciar();

        JOptionPane.showMessageDialog(null, "Quando quiser parar clique no OK");

        JOptionPane.showMessageDialog(null, String.format("%s segundos ...", timer.getSegundos()));

        System.exit(0);
    }
}

po cara vou tentar fazer com o esse exemplo, mas essa variavel segundos ta criada na classe Timer olha como vc ta usando ela na classe tempo

tem como vc me explicar seu exemplo cara sem querer ser chato, vlw desde ja

Então a classe Tempo é uma classe privada da Timer e tem acesso as suas variaveis globais.

A classe Tempo extende a TimerTask que por sua vez é usada pelo objeto Timer(que faz a interação a cada 1000 millesegundos).

Ou seja a cada 1 segundo a classe Tempo é chamada, ou seja incrementa uma unidade na variavel Segundo (global da nossa classe timer).

Desculpa eu deu nomes meios parecidos …