1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| public class Demo {
public static void main(String[] args) {
new Demo();
}
private final JLabel labelIntermediaire;
private final JLabel labelFinal;
private final JButton startButton;
private final JButton stopButton;
private SwingWorker<String, String> swingworker;
public Demo() {
JFrame frame = new JFrame("Démo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().setLayout(new GridBagLayout());
JPanel ui = new JPanel(new GridBagLayout());
frame.add(ui);
labelIntermediaire = new JLabel();
labelFinal = new JLabel();
startButton = new JButton("Start");
stopButton = new JButton("Stop");
stopButton.setEnabled(false);
GridBagConstraints gbc = new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1, 1,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(3, 3, 3, 3), 0, 0);
ui.add(labelIntermediaire, gbc);
ui.add(labelFinal, gbc);
ui.add(startButton, gbc);
ui.add(stopButton, gbc);
frame.setSize(300, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
startButton.addActionListener(e -> start());
stopButton.addActionListener(e -> stop());
frame.addWindowListener(new WindowAdapter() {
public void windowClosed(java.awt.event.WindowEvent e) {
stop();
};
});
}
private void stop() {
if (swingworker!=null) swingworker.cancel(true);
}
private void start() {
startButton.setEnabled(false);
stopButton.setEnabled(true);
swingworker = new SwingWorker<String, String>() {
@Override
protected String doInBackground() throws Exception {
// simulation tâche longue
String result = "";
for (int i = 0; i < 10/*000*/; i++) {
result = String.valueOf(i);
publish(result); // publication résultat intermédiaire
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
return result;
}
@Override
protected void process(List<String> chunks) {
// mise à jour résultat intermédiaire
if (!chunks.isEmpty()) {
labelIntermediaire.setText(chunks.get(chunks.size() - 1));
}
}
@Override
protected void done() {
stopButton.setEnabled(false);
startButton.setEnabled(true);
labelIntermediaire.setText("");
if ( isCancelled()) {
labelFinal.setText("Tâche interrompue");
}
else {
try {
labelFinal.setText("Tâche terminée : " + get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
};
labelFinal.setText("En cours...");
swingworker.execute();
}
} |
Partager