Ho creato il mio esempio SwingWorker per familiarizzare con il suo funzionamento.Come faccio a far funzionare correttamente il mio esempio SwingWorker?
Quello che voglio fare è il seguente: Quando si fa clic sul pulsante Voglio che venga visualizzata una barra di avanzamento fino a quando l'attività è terminata Voglio semplicemente rimuovere la barra di avanzamento e aggiungere una stringa alla finestra di dialogo.
Quando si fa clic sul pulsante, la barra di avanzamento si apre ma non scompare mai. (Mai rimuove la barra di avanzamento dopo 10 secondi e non mette l'etichetta verso l'alto)
Ecco uno SSCCE:
package swingtesting;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
public class SwingTesting {
/**
* Creates a frame that will hold a simple button to make use of SwingWorker
*/
public static void main(String[] args) {
// TODO code application logic here
JFrame frame = new JFrame();
JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new GuiWorker().execute();
}
});
button.setText("Test Me");
frame.getContentPane().add(button);
frame.pack();
frame.setVisible(true);
}
}
class GuiWorker extends SwingWorker<Integer, Integer> {
/*
* This should just create a frame that will hold a progress bar until the
* work is done. Once done, it should remove the progress bar from the dialog
* and add a label saying the task complete.
*/
private JFrame frame = new JFrame();
private JDialog dialog = new JDialog(frame, "Swingworker test", true);
private JProgressBar progressBar = new JProgressBar();
public GuiWorker() {
progressBar.setString("Waiting on time");
progressBar.setStringPainted(true);
progressBar.setIndeterminate(true);
dialog.getContentPane().add(progressBar);
dialog.pack();
dialog.setVisible(true);
}
@Override
protected Integer doInBackground() throws Exception {
Thread.sleep(10000);
return 0;
}
@Override
protected void done() {
JLabel label = new JLabel("Task Complete");
dialog.getContentPane().remove(progressBar);
dialog.getContentPane().add(label);
}
}
È possibile dare un'occhiata a [questa risposta] (http://stackoverflow.com/questions/8916721/java-swing-update-label/8917565#8917565) e confronta con il tuo codice. Il tutorial di Swing contiene anche un esempio (il collegamento è disponibile nella classe javadoc di 'JProgressBar') – Robin