Usar Thread de uma classe em outra classe

2 respostas
Ermin

Olá galera, tenho um classe Tempo (conforme abaixo) e ela tem seus métodos e uma thread, ao rodar essa classe ele mostra um contador de tempo em um Formzinho, pois bem, gostaria de usar essa classe para fazer esse reloginho funconar em outro frame q está dentro do mesmo pacote da classe Tempo. Gostaria q esse reloginho aparecesse em uma Label dentro de outro Form e fisesse a contagem normalmente, alguém pode dar uma força? Agradelo muito!!!

package hora;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

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

/**
*
* @author ermin
*/
public class Tempo extends JPanel {

    JLabel label;

    DateFormat dateFormat;

    Calendar calendar;

    public Tempo() {
        this.dateFormat = new SimpleDateFormat("HH:mm:ss");
        this.calendar = Calendar.getInstance();
        this.calendar.set(Calendar.MILLISECOND, 0);  
        this.calendar.set(Calendar.SECOND, 0);
        this.calendar.set(Calendar.MINUTE, 0);
        this.calendar.set(Calendar.HOUR_OF_DAY, 0);

        this.initialize();

    }

    protected void initialize() {
        this.setLayout(null);
        this.add(this.getButton());
        this.go();
    }

    public JLabel getButton() {
        if (this.label == null) {
            this.label = new JLabel(getTime());
            this.label.setBounds(10, 10, 100, 22);
        }
        return this.label;
    }

    public void go() {
        ActionListener action = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Tempo.this.label.setText(getTime());
            }
        };
        Timer t = new Timer(1000, action);
        t.start();
    }

    public String getTime() {
        this.calendar.add(Calendar.SECOND, 1);
        return this.dateFormat.format(this.calendar.getTime());
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new Tempo());
        frame.setSize(300, 200);
        frame.setVisible(true);
        
    }

   
}

2 Respostas

M

Se você quiser apenas adicionar o seu painel em outra janela, basta fazer o seguinte na outra classe (supondo que ela estenda JFrame):

this.add(new Tempo());

Se você quer adicionar o tempo em um JLabel, sugiro que separe as responsabilidades. Por exemplo, faça algo assim:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

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

public class Tempo {

    private JLabel label;
    private DateFormat dateFormat;

    public Tempo(JLabel label) {
    	this.label = label;
        dateFormat = new SimpleDateFormat("HH:mm:ss");
    }
    
    public void start() {
		ActionListener action = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Tempo.this.label.setText(getTime());
            }
        };
        Timer t = new Timer(1000, action);
        t.start();
	}

    private String getTime() {
        return dateFormat.format(new Date());
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel l = new JLabel("Hora atual");
        frame.add(l);
        frame.pack();
        frame.setVisible(true);
        // desse jeito qualquer label pode ter a informação de horário
        new Tempo(l).start();
    }

}
Ermin

marco não consegui nenhum avanço com o problema, tipo o segundo Form tem q ficar atualizando a hora tbm.
vlw!

Criado 13 de dezembro de 2010
Ultima resposta 13 de dez. de 2010
Respostas 2
Participantes 2