Would not it be better to implement it with a timer?
I give you an example:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.Timer;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Eduardo Isaac Ballesteros
*/
public class TimerEjemplo2 {
Timer timer;
int contador = 0;
int valorMaximo = 100;
int valorInicial = 0;
public static void main(String[] args) {
TimerEjemplo2 timerEjemplo2 = new TimerEjemplo2();
}
public TimerEjemplo2() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
final JLabel label = new JLabel("", JLabel.CENTER);
Hilo hilo = new Hilo("test");
hilo.start();
timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setText(String.valueOf(valorInicial));
valorInicial++;
if (valorInicial == valorMaximo) {
timer.stop();
}
}
});
timer.start();
JOptionPane.showConfirmDialog(null, label, "Ejemplo", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
}
});
}
}
A dirty solution with Thread would be like this:
public class Sistema {
private static int contador = 100;
/**
* @return the contador
*/
public static int getContador() {
return contador;
}
/**
* @param aContador the contador to set
*/
public static void setContador(int aContador) {
contador = aContador;
}
}
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
/**
*
* @author Eduardo Isaac Ballesteros
*/
public class Hilo extends Thread {
JLabel label;
public Hilo(JLabel pLabel) {
this.label = pLabel;
}
@Override
public void run() {
int cantMaxima = 100;
int iterador = 0;
while (iterador < cantMaxima) {
Sistema.setContador(Sistema.getContador() - 1);
label.setText("Desde hilo: " + String.valueOf(Sistema.getContador()));
iterador++;
try {
sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Hilo.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
import javax.swing.JLabel;
import javax.swing.JOptionPane;
/**
*
* @author Eduardo Isaac Ballesteros
*/
public class TimerEjemplo3 {
public static void main(String[] args) {
TimerEjemplo3 timerEjemplo3 = new TimerEjemplo3();
}
public TimerEjemplo3() {
final JLabel label = new JLabel("", JLabel.CENTER);
Hilo hilo = new Hilo(label);
hilo.start();
JOptionPane.showConfirmDialog(null, label, "Ejemplo", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
}
}