I want to open a JFrame that has a jpanel with two jlabel, with a method that loops and rewrites those labels. Of course in the loop I have a thread.sleep, BUT I can't figure it out, my thread begins to run 1.. 2.. 3.. and when this finished the JFrame opens.
Here is my code I have wrote so far:
FrmPruebaPlanillon vtnPruebaPlanillon = new FrmPruebaPlanillon();
vtnPruebaPlanillon.setVisible(true);
boolean infinito = true;
while(infinito)//todo ver con cuidado
{
//enviamos los comando por fila para podrer rellenar los datos del
//taximetro con el boleto generado
System.out.println(FrmPrincipal.linea()+"Inició la prueba "+ (contadorDePrueba+1));
//pp.getLblNEnvio().setText((contadorDePrueba+1)+"");
vtnPruebaPlanillon.getLblNEnvio().setText((contadorDePrueba+1)+"");
vtnPruebaPlanillon.getLblDatoEnviado().setText(fila[contadorDePrueba]);
//pp.getLblDatoEnviado().setText(fila[contadorDePrueba]);
//#######################################################################3
pruebaPorTabla(tipoPrueba, datosCsv);
//pruebaPorFila(tipoPrueba, fila[contadorDePrueba]);
//vtnFrmBoleto.setParametrosPrueba(tipoPrueba, tblPrueba, numeroPrueba, taximetro, empresa);
//pone un numero de prueba en la ventana boleto
if(contadorDePrueba == 0)
{
//vtnFrmBoleto.getLblNprueba().setText((String) tblPrueba.getModel().getValueAt(0, 0));
}
//vtnFrmBoleto.setVisible(true);
contadorDePrueba++;
if(contadorDePrueba==dataTabla.length-1)
{
System.out.println("numero de lineas enviadas"+contadorDePrueba);
infinito=false;
}
}
Of course, calling Thread.sleep();
on EDT causes such an unpredictable behaviour as I pointed in my commnet. Use proper component instead. In this case, swing Timer
. Here is a small demo for you:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class RepaintDemo {
JFrame frame = new JFrame("Repaint demo");
JLabel labelFirst = new JLabel("First label");
JLabel labelSecond = new JLabel("Second label");
JLabel[] labels = { labelFirst, labelSecond };
JPanel panel = new JPanel();
Timer timer;
int i = 0;
public RepaintDemo() {
// Wait for 3 seconds and then add label
timer = new Timer(3000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.add(labels[i]);
panel.repaint();
panel.revalidate();
i++;
if (i == labels.length) {
timer.stop();
}
}
});
// Adds next label after every 3 seconds
timer.setDelay(3000);
timer.setRepeats(true);
timer.start();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new RepaintDemo();
}
});
}
}
As you can see, JFrame
will appear upon startup. After 3 seconds, first label will appear. And after another 3 seconds, second label will appear too.