Barra de progresso usando threads?

1 resposta
B

Olá pessoal, gostaria de saber de alguem que já trabalhou diretamente com threads e se é possivel mostrar o progresso de uma migracao usando threads, pra mostrar simultaneamente o % ja migrado na tela ao mesmo tempo que o sistema faz a migracao.
Agradeço qualquer colaboração.
Obrigado

1 Resposta

T
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;


class Processamento implements Runnable {
    private JProgressBar jpb;
    private boolean interrupted = false;
    
    public Processamento() {
    }
    public void setProgressBar(JProgressBar jpb) {
        this.jpb = jpb;
    }
    public void setInterrupted (boolean interrupted) {
        this.interrupted = interrupted;
    }
    
    public void run() {
        for (int i = 0; i &lt 100 && !interrupted; ++i) {
            try { Thread.sleep (100); } catch (InterruptedException ex) {}
            jpb.setValue (i);
        }
    }
}

class TesteProgressBar extends JFrame {
    JProgressBar jpb;
    Processamento proc;
    Thread thr;
    
    public void startProcessing() {
        proc.setInterrupted(false);
        thr = new Thread (proc);
        thr.start();
    }
    public void stopProcessing() {
        proc.setInterrupted(true);
        try {
            if (thr != null)
                thr.join();
        } catch (InterruptedException ex) {
        }
        jpb.setValue (0);
    }

    
    public TesteProgressBar() {
        super();
        setBounds (new Rectangle (200, 200, 300, 200));
        setPreferredSize (new Dimension (300, 200));
        setTitle ("Exemplo de Progress Bar");
        setDefaultCloseOperation (WindowConstants.EXIT_ON_CLOSE);
        Container contentPane = getContentPane();
        contentPane.setLayout (new FlowLayout());
        JLabel jl = new JLabel ("Progress Bar");
        contentPane.add (jl);        
        jpb = new JProgressBar();
        contentPane.add (jpb);
        JButton jb = new JButton ("Click here");
        contentPane.add (jb);
        
        jb.addActionListener (new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                startProcessing();
            }
        });
        JButton jbCancel = new JButton ("Cancel");
        contentPane.add (jbCancel);
        jbCancel.addActionListener (new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                stopProcessing();
            }
        });
        proc = new Processamento();
        proc.setProgressBar (jpb);
    }
    
    
    public static void main(String[] args) {
        TesteProgressBar tb = new TesteProgressBar();
        tb.pack();
        tb.setVisible(true);
    }
}
Criado 7 de novembro de 2006
Ultima resposta 7 de nov. de 2006
Respostas 1
Participantes 2