Ciao. Premetto che non mi sono mai cimentato in cose come questa. Cmq il problema sta che la sleep blocca l'actionListener(e anche l'interfaccia grafica), quindi vanno usati altri thread.
Questa e' una soluzione che funziona, pero' non so se e' il modo migliore di procedere.
Valuta tu.
codice:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class NewClass3 extends JFrame{
private JLabel[] labels;
private JLabel lab1;
private JLabel lab2;
private JLabel lab3;
private JButton b;
private JPanel pan;
/** Creates a new instance of NewClass3 */
public NewClass3() {
pan = new JPanel();
lab1 = new JLabel("Uno");
lab2 = new JLabel("Due");
lab3 = new JLabel("Tre");
labels = new JLabel[]{lab1,lab2,lab3};
b = new JButton("Let's go");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Faccio un nuovo thread
new Thread(new Runnable() {
//Faccio un contatore
int i=0;
public void run() {
//Per ogni label
for(i=0;i<labels.length; i++) {
//Aspetto un secondo
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//E poi visualizzo la label
SwingUtilities.invokeLater(new Runnable() {
public void run() {
labels[i].setVisible(true);
}
});
}
}
//Faccio partire il thread
}).start();
}
});
lab1.setVisible(false);
pan.add(lab1);
lab2.setVisible(false);
pan.add(lab2);
lab3.setVisible(false);
pan.add(lab3);
pan.add(b);
this.add(pan);
this.setSize(400,400);
this.setDefaultCloseOperation(this.DISPOSE_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
new NewClass3();
}
}