D. Olivier
Université du Havre
Il y a au moins 4 threads utilisés dans une application graphique
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class EDTEtThreadInitial extends JFrame {
public EDTEtThreadInitial() {
// A faire
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
// A Faire : les initialisations
SwingUtilities.invokeLater(new Runnable() {
public void run() {
EDTEtThreadInitial f = new EDTEtThreadInitial();
f.setVisible(true);
}
});
}
}
EDTEtThreadInitial.java
public class DemoJProgressBar3 extends JFrame {
JProgressBar barre;
public DemoJProgressBar3() {
super("JProgressBar et les threads");
// Le layout
setLayout(new BorderLayout());
// Les éléments de l'interface
barre = new JProgressBar();
JButton bouton = new JButton("Charger");
// On ajoute les éléments
add(bouton, BorderLayout.CENTER);
add(barre, BorderLayout.SOUTH);
// Ajout d'un écouteur sur le bouton
bouton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Le thread d'exécution de la tache longue
Thread t = new Thread() {
public void run() {
Traitement tache = new Traitement(true);
tache.execute(barre);
}
};
t.start();
}
});
// Gestion fermeture de la fenêtre
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
DemoJProgressBar3 fenetre = new DemoJProgressBar3();
fenetre.setVisible(true);
}
});
}
}
Traitement.javaLes composants de Swing doivent être manipulés dans l'EDT.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
public class DemoJProgressBar5 extends JFrame {
JProgressBar barre;
public DemoJProgressBar5() {
super("JProgressBar et les threads");
// Le layout
setLayout(new BorderLayout());
// Les éléments de l'interface
barre = new JProgressBar();
final JButton bouton = new JButton("Charger");
// On ajoute les éléments
add(bouton, BorderLayout.CENTER);
add(barre, BorderLayout.SOUTH);
// Ajout d'un écouteur sur le bouton
bouton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread t = new Thread() {
public void run() {
Traitement tache = new Traitement(true);
tache.execute(barre);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
bouton.setBackground(Color.GRAY); //Dans l'EDT
}
});
}
};
t.start();
}
});
// Gestion fermeture de la fenêtre
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
DemoJProgressBar5 fenetre = new DemoJProgressBar5();
fenetre.setVisible(true);
}
});
}
}
Traitement.java