Threads - Relogio + Texto

4 respostas
F

Pessoal, estou fazendo um trabalho de aula, e preciso utilizar threads, consegui, utilziando NetBeans IDE 5.5 e J2EE, o relogio aparece e o texto é editado, o unico problema meu relogio não atuliza, quem utiliza NetBeans ele tem um JFrame q podem ser adicionados componentes, vou por os codigos aki:

Classe Relogio
import java.util.*;
import javax.swing.*;

public class Relogio extends Thread{
    
    int hora,minuto,segundo;
    Long res =  System.currentTimeMillis();
    Date data = new Date( res );
    JTextField field;
    
    public Relogio( JTextField tf ){
        
        field = tf;
        hora = 0;
        minuto = 0;
        segundo = 0;
    }
    
    public void run(){
        
        while(true){
            
            segundo = data.getSeconds();
            minuto = data.getMinutes();
            hora = data.getHours();
            
            String ho = hora + ":" + minuto + ":" + segundo;
            ho = String.format("%trS",res);
            field.setText( ho + "" );
            
            try{
                
                sleep(1);
                
            }catch( InterruptedException e ){}
            
        }
        
    }
    
    public JTextField rHour(){
        
        String ho = hora + ":" + minuto + ":" + segundo;
        ho = String.format("%trS",res);
        field.setText( ho + "" );
        
        return field;
        
    }
    
}
Classe EscreveChar
import javax.swing.*;

public class EscreveChars extends Thread{
    
    int t;
    char c;
    JTextArea area;
    
    public EscreveChars( JTextArea ta ){
        
        area = ta;
        c = 'a';
        t = 0;
        
    }
    
    public void run(){
        
        while(true){
            
            
            if( t > 25 ){
                
             area.append( c + "\n" );
            c++;   
            t = 0;    
            }else{
                
            area.append( c + "" );
            c++;
            t++;
            }
            
              try{
                
                sleep(100);
                
            }catch( InterruptedException e ){}     
                    
        }
        
    }
    
}
Classe Rodando
/*
 * Rodando.java
 *
 * Created on 30 de Março de 2007, 08:21
 */

/**
 *
 * @author  felix
 */
public class Rodando extends javax.swing.JFrame {
    
    Relogio rel;
    EscreveChars ec;
    int stPres;
    
    /** Creates new form Rodando */
    public Rodando() {
        initComponents();
        rel = new Relogio( jTextField1 );
        ec = new EscreveChars( jTextArea1 );
        stPres = 0;
    }
    
    /** 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.
     */
    // <editor-fold defaultstate="collapsed" desc=" Código Gerado ">                          
    private void initComponents() {
        jTextField1 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jButton1.setText("Start");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Stop");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel1.setText("Hora Atual:");

        jLabel2.setText("Texto:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addGap(23, 23, 23)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(22, 22, 22))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(15, 15, 15)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(23, Short.MAX_VALUE))
        );
        pack();
    }// </editor-fold>                        
    
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
// TODO adicione seu código de manipulação aqui:
        rel.stop();
        ec.stop();
        stPres = 1;
        
    }                                        
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
// TODO adicione seu código de manipulação aqui:
        
        if( stPres == 1 ){
            
            rel = new Relogio( jTextField1 );
            ec = new EscreveChars( jTextArea1 );
            stPres = 0;
            
        }
        rel.start();
        ec.start();
        
        
        
    }                                        
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Rodando().setVisible(true);
            }
        });
    }
    
    // Declaração de variáveis - não modifique                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    // Fim da declaração de variáveis                   
    
}

espero que alguem possa me ajudar, Somente o Relogio esta com problema, mas postei todo o codigo aki, o relogio precisa atualizar segundo a segundo, adradeço desde já

4 Respostas

T

Em vez de deixar uma thread com sleep de 1 milissegundo (cruz credo), use um javax.swing.Timer, com intervalo de 0,5 segundos.

V

Que tal 3 implementações do mesmo exemplo de algo similar? Um deles usando a classe Thread diretamente outro usando timer da classe útil e finalmente um com a sugestão do Thingol usando o timer do Swing?

F

vou compartilhar meu novo codigo esse funcionou perfeitamenta

import java.util.*;
import javax.swing.*;

public class Relogio extends Thread{
    
    long hora;
    JTextField field;
    
    public Relogio(){
        
    }
    
    public Relogio( JTextField tf ){//aceita um TextField como parametro para mostrar no Frame
        
        field = tf;

    }
    
    public void run(){
        
        while(true){
            
            
            hora = System.currentTimeMillis();
            String agora = String.format("%trS",hora);
            field.setText(agora + "");//joga para o TextField
            
            try{
                
                sleep(1000);
                
            }catch( InterruptedException e ){}
            
        }
        
    }
    
 
}

Esse ficou o codigo da classe relogio e funcionou

V

Cuidado na hora de atualizar objetos gráficos fora da thread da AWT, pois os objetos do Swing não são thread-safe.
O correto é, ao invés de:

field.setText(agora + "");//joga para o TextField

Fazer:

EventQueue.invokeLater() {new Runnable() { public void run() { field.setText(agora + ""); } }

Isso empilhará um pedido na fila de mensagens da Awt (EventQueue), para que atualize a caixa de textos no momento adequado, dentro de sua própria thread. Não fazer isso pode gerar um comportamento bastante estranho na sua aplicação, como letras embaralhadas, cores estranhas ou simplesmente sujeira na tela. E o pior, pode só acontecer de vez enquando (geralmente quando o seu cliente/chefe estiver olhando)…

Criado 30 de março de 2007
Ultima resposta 30 de mar. de 2007
Respostas 4
Participantes 3