Finalizar uma Thread!

5 respostas
Elivelton_Oliveira

Não consigo finalizar uma thread:

new Thread(){
          @Override
          public void run(){
              for (int i = 0; i < 102; i++){
                  try {
                      sleep(101);
                      progressoEmail.setValue(i);
                      if(progressoEmail.getValue() <= 25){
                          txtEmail.setText("Carregando e-mail...");
                      }else if(progressoEmail.getValue() <= 50){
                          txtEmail.setText("Conectando com Servidor SMTP...");
                      }else if(progressoEmail.getValue() <= 75){
                          txtEmail.setText("Abrindo e-mail...");
                      }else if(progressoEmail.getValue() <= 99){
                          txtEmail.setText("Enviando e-mail...");
                      }else if(progressoEmail.getValue() <= 100){
                          txtEmail.setText("Email enviado com Sucesso!");                      
                      }else if (progressoEmail.getValue() <= 101){
                          btnFechar.doClick();
                      }

                  } catch (Exception e) {
                      
                  }
              }
          }
       
        }.start();

Esse código está dentro da ação do botão. já coloquei no método construtor da classe Frame, mas mesmo assim a Thread não para, além disso queria que a janela fechasse quando a barra de progresso parar. Não estou conseguindo.

:frowning:

5 Respostas

staroski

Sua implementação está muito estranha, não faz sentido aquele seu laço até 102 nem o sleep de 101 milissegundos.

Você está atualizando seus campo de texto com base no valor da progressbar, acho que você está pensando ao contrário, é sua progressbar que deve ser atualizado a medida que suas tarefas, processos ou etapas são concluídos.
Não faz sentido monitorar o valor da progressbar pra saber o que está sendo executado no momento.

Elivelton_Oliveira

Entendi a sua posição!

Mas essa foi a única forma que eu consegui fazer com que a progressbar funcionasse.

Eu usei o 102 no for e 101 no sleep porque depois eu modifiquei o código e coloquei um if, caso a progressbar fosse > que 101, dentro do if coloquei um dispose, para fechar o frame, mas nisso não deu certo e nem a thread para.

peczenyj

isto não faz o menor sentido.

vc ja sabe o valor, pra que pegar de novo? use apenas i dentro do if ué.

agora vc esta assumindo que depois dessa periodo todo vc ja enviou o email…

eu usaria eventos nesse caso para coordenar as coisas, mas tem mais alguma coisa estranha ai. e vc some com qq exception

Elivelton_Oliveira

Entendo!

Vou fazer aqui um teste de outra forma, usando uma classe.

Elivelton_Oliveira

Assistir alguns vídeos no Youtube, e parece que atende o que eu quero !

Minha Classe Progresso:

package br.com.progresso;

import br.com.telas.TelaTeste;

import javax.swing.JLabel;

import javax.swing.JProgressBar;

import javax.swing.JTextArea;

import javax.swing.SwingWorker;

import sun.management.snmp.jvminstr.JvmThreadInstanceEntryImpl;

/**
*

  • @author elivelton.s
    */
    public class Progresso extends SwingWorker<Integer, String>{

    private JLabel label;
    
    private JProgressBar Progresso;
    
    private JLabel label2;
    
    public Progresso(JLabel label, JProgressBar Progresso, JLabel label2) {
    
    this.label = label;
    
    this.Progresso = Progresso;
    
    this.label2 = label2;
    
    }
    
    <a class="mention" href="/u/override">@Override</a>
    
    protected Integer doInBackground() throws Exception {
    
    getLabel2().setVisible(true);
    
    getLabel().setVisible(true);
    
    getProgresso().setIndeterminate(true);
    
    try{
     for(int i= 0; i<11; i++){
         if(i == 1){
           label2.setText("Enviar e-mail...");  
         }else if(i == 5){
            label2.setText("Conectando com o Servidor..."); 
         }else if(i >= 10){
            label2.setText("Email enviado com Sucesso!"); 
         }
         Thread.sleep(1000);
     }
     
     }catch(Exception ex){
         System.out.println("Erro"+ex.getMessage());
     }
    
     getLabel().setVisible(false);
     getProgresso().setIndeterminate(false);
     
     return 0;
    

    }

    /**

    • @return the label
      */
      public JLabel getLabel() {
      return label;
      }

    /**

    • @param label the label to set
      */
      public void setLabel(JLabel label) {
      this.label = label;
      }

    /**

    • @return the Progresso
      */
      public JProgressBar getProgresso() {
      return Progresso;
      }

    /**

    • @param Progresso the Progresso to set
      */
      public void setProgresso(JProgressBar Progresso) {
      this.Progresso = Progresso;
      }

    /**

    • @return the label2
      */
      public JLabel getLabel2() {
      return label2;
      }

    /**

    • @param label2 the label2 to set
      */
      public void setLabel2(JLabel label2) {
      this.label2 = label2;
      }

    /**

    • @return the label
      */

}

Meu Frame de Teste:

package br.com.telas;

import br.com.conexao.ConnectionFactory;

import br.com.dao.DestinoDao;

import br.com.destino.Destino;

import br.com.progresso.Progresso;

import java.awt.Cursor;

import java.beans.PropertyChangeEvent;

import java.beans.PropertyChangeListener;

import java.sql.Connection;

import java.sql.Date;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.text.SimpleDateFormat;

import javax.swing.JOptionPane;

import javax.swing.SwingWorker;

/**
*

  • @author elivelton.s
    */
    public class TelaTeste extends javax.swing.JFrame {

    /**

    • Creates new form TelaTeste
      */
      public TelaTeste() {
      initComponents();
      txtprogresso.setVisible(true);
      }
    public void fechar(){
    
    dispose();
    
    }
    
    /**
    
    • 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)
      
      // 
      
      private void initComponents() {
      
      jButton1 = new javax.swing.JButton();
      
      txtProcess = new javax.swing.JLabel();
      
      txtprogresso = new javax.swing.JProgressBar();
      
      txtArea = new javax.swing.JLabel();
      

      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

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

      txtProcess.setText(“Processando…”);

      txtprogresso.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
      
      txtprogresso.setString("");
      
      txtprogresso.setStringPainted(true);
      

      txtArea.setFont(new java.awt.Font(“Tahoma”, 1, 11)); // NOI18N
      txtArea.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

      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(37, 37, 37)
      
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
      
      .addComponent(txtprogresso, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      
      .addGroup(layout.createSequentialGroup()
      
      .addComponent(txtProcess)
      
      .addGap(155, 155, 155)
      
      .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE))
      
      .addComponent(txtArea, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
      
      .addContainerGap(52, Short.MAX_VALUE))
      
      );
      
      layout.setVerticalGroup(
      
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      
      .addGroup(layout.createSequentialGroup()
      
      .addGap(32, 32, 32)
      
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
      
      .addComponent(txtProcess)
      
      .addComponent(jButton1))
      
      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
      
      .addComponent(txtprogresso, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
      
      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
      
      .addComponent(txtArea, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
      
      .addContainerGap(227, Short.MAX_VALUE))
      
      );
      

      pack();
      }//

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    
    // TODO add your handling code here:
    
    Progresso p = new Progresso(txtProcess, txtprogresso, txtArea);
    
    p.addPropertyChangeListener(new PropertyChangeListener() {
         @Override
         public void propertyChange(PropertyChangeEvent evt) {
             if(evt.getPropertyName().equalsIgnoreCase("Progresso")){
                 setCursor(new Cursor(Cursor.WAIT_CURSOR));
             }else{
                 if(evt.getPropertyName().equalsIgnoreCase("State")){
                     switch((SwingWorker.StateValue) evt.getNewValue()){
                         case DONE:
                             setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                             break;
                         case STARTED:
                             setCursor(new Cursor(Cursor.WAIT_CURSOR));
                             break;
                         case PENDING:
                             break;
                     }
                 } 
             }
         }
     });
     
     
     
     p.execute();
    

    }

    /**

    • @param args the command line arguments
      /
      public static void main(String args[]) {
      /
      Set the Nimbus look and feel /
      //
      /
      If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.

      • For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
        */
        try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if (“Nimbus”.equals(info.getName())) {
        javax.swing.UIManager.setLookAndFeel(info.getClassName());
        break;
        }
        }
        } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(TelaTeste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(TelaTeste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(TelaTeste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(TelaTeste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //
      /* Create and display the form */
      
      java.awt.EventQueue.invokeLater(new Runnable() {
      
      public void run() {
      
      new TelaTeste().setVisible(true);
      
      }
      
      });
      
      }
      
    // Variables declaration - do not modify
    
    private javax.swing.JButton jButton1;
    
    private javax.swing.JLabel txtArea;
    
    private javax.swing.JLabel txtProcess;
    
    private javax.swing.JProgressBar txtprogresso;
    
    // End of variables declaration
    
    }
    

Agora só estou tendo trabalho para usar DISPOSE(); para fechar quando terminar.

Criado 19 de outubro de 2016
Ultima resposta 20 de out. de 2016
Respostas 5
Participantes 3