Bonjour,

Je développe un bloc actualité avec le texte qui déroule automatiquement avec Swing.
J'ai un problème de scintillement. J'ai parcourus le forum et internet et essayé plusieurs solutions:
- double buffering
- protected void paintComponent(Graphics g) ou public void paint(Graphics g)
- le revalidate() avant le repaint()
Je n'y arrive pas.

Ci-dessous le JPanel, la JDialog, le SwingWorker et l'actu

Merci de votre aide

Code : Sélectionner tout - Visualiser dans une fenêtre à part
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.font.TextAttribute;
import java.text.AttributedString;
import java.util.Map;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
 
public class ActuJPanel extends javax.swing.JPanel {
 
    /** Creates new form ActuJPanel */
    public ActuJPanel(JDialog parent) {
        initComponents();
        this.parent = parent;
 
        lstActu = getActus();
 
    }
 
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                          
    private void initComponents() {
 
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
    }// </editor-fold>                        
 
    private void formMouseClicked(java.awt.event.MouseEvent evt) {                                  
 
        if(lstRectangle!=null){
            Map<Rectangle,Actu> lstTemp = new HashMap<Rectangle,Actu>();
            lstTemp.putAll(lstRectangle);
            for(Map.Entry<Rectangle,Actu> clevaleur : lstTemp.entrySet()){
                if(clevaleur.getKey().contains(evt.getPoint())){
                    JOptionPane.showMessageDialog(parent,"Actu : " + clevaleur.getValue().getTitre());
                }
            }
        }
 
    }                                 
 
 
    // Variables declaration - do not modify                     
    // End of variables declaration                   
    private SwingWorkerApo worker;
    private int y1;
    private Map<Rectangle, Actu> lstRectangle = new HashMap<Rectangle,Actu>();
    private List<Actu> lstActu;
    private int retraitGauche = 15;
    private int interligne = 3;
    private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    private JDialog parent;
    private BufferedImage bimg;
    private int maxY = -15;
    private int tempAttenteDefile = 100;
 
    public void lanceDefile(){
        worker = new SwingWorkerApo() {
            public Object construct() {
                return doWork();
            }
        };
        worker.start();
 
 
    }
 
    private Object doWork() {
        try {
            boolean continu = true;
 
            y1=this.getSize().height;
 
            while(continu){
 
 
                repaint();
                revalidate();
 
                Thread.sleep(tempAttenteDefile);
                y1--;
                if(y1<maxY){
                    y1=this.getSize().height;
                }
            }
        }
        catch (InterruptedException e) {
            return "Interrupted";  // SwingWorker.get() returns this
        }
        return "All Done";         // or this
    }
 
    protected void paintComponent(Graphics g){
        buffImage();
        if(bimg!=null){
            g.drawImage(bimg, 0,0,this);
        }
    }
 
    public void buffImage(){
 
 
        Font fontDate = new Font("courier new",Font.PLAIN,12);
        Color couleurDate = Color.DARK_GRAY;
        FontMetrics fontMetricsDate = getFontMetrics(fontDate);
        int hauteurDate = fontMetricsDate.getHeight();
 
        Font fontTitre = new Font("courier new",Font.PLAIN,12);
        Color couleurTitre = Color.BLUE;
        FontMetrics fontMetricsTitre = getFontMetrics(fontTitre);
        int hauteurTitre = fontMetricsTitre.getHeight();
        int nbCarTitre = (this.getWidth()-(retraitGauche*2)) / fontMetricsTitre.charWidth('W');
 
        Font fontResume = new Font("courier new",Font.PLAIN,12);
        Color couleurResume = Color.BLACK;
        FontMetrics fontMetricsResume = getFontMetrics(fontResume);
        int hauteurResume = fontMetricsResume.getHeight();
        int nbCarResume = (this.getWidth()-(retraitGauche*2)) / fontMetricsResume.charWidth('W');
 
        Dimension d = getSize();
        if (d.width <= 0 || d.height <= 0) {
            return;
        }
        if (bimg == null ||
            bimg.getWidth()  != d.width ||
            bimg.getHeight() != d.height) {
            bimg = getGraphicsConfiguration().createCompatibleImage(d.width, d.height);  
        }
        Graphics2D gmem = bimg.createGraphics();
        gmem.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
        gmem.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        gmem.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
 
        //couleur de fond blanc
        gmem.setColor(this.getBackground());
        gmem.fillRect(0,0,this.getSize().width,this.getSize().height);
 
        lstRectangle.clear();
        int tempY = y1;
        for(Actu actu : lstActu){
 
            //date
            gmem.setColor(couleurDate);
            gmem.setFont(fontDate);
            gmem.drawString(sdf.format(actu.getDate().getTime()),retraitGauche,tempY);
            tempY+=hauteurDate+interligne;
 
            //titre
            List<String> lstTitre = formatStringForJava2d(actu.getTitre(),nbCarTitre);
            if(lstTitre!=null){
                for(String titre : lstTitre){
                    gmem.setColor(couleurTitre); //couleur du texte
                    gmem.setFont(fontTitre); //Police+taille du texte
                    AttributedString as = new AttributedString(titre);
                    as.addAttribute(TextAttribute.FONT, fontTitre);
                    as.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
                    as.addAttribute(TextAttribute.FOREGROUND, couleurTitre);
                    gmem.drawString(as.getIterator(),retraitGauche,tempY);
                    char[] tabChaine = titre.toCharArray();
                    int largeur = fontMetricsTitre.charsWidth(tabChaine,0,tabChaine.length) + retraitGauche;
                    lstRectangle.put(new Rectangle(retraitGauche,tempY-hauteurTitre,largeur-retraitGauche,hauteurTitre),actu);
                    tempY+=hauteurTitre+interligne;
                }
            }
            //resume
            List<String> lstResume = formatStringForJava2d(actu.getResume(),nbCarResume);
            if(lstResume!=null){
                for(String resume : lstResume){
                    gmem.setColor(couleurResume);
                    gmem.setFont(fontResume);
                    gmem.drawString(resume,retraitGauche,tempY);
                    tempY+=hauteurResume+interligne;
 
 
 
                }
            }
            //ligne séparation
            gmem.setColor(Color.DARK_GRAY);
            gmem.drawLine(5,tempY, this.getWidth()-10,tempY ) ;
            tempY+=interligne + interligne + interligne + interligne;
        }
 
        if(y1==0){
            maxY = -tempY;
        }
        gmem.dispose();
        //updateStatus();
        if (Thread.interrupted()) {
 
        }	
    }
 
 
    private List<Actu> getActus(){
        List<Actu> lstActu = new ArrayList<Actu>();
 
        Actu actu = new Actu();
        Calendar cal = Calendar.getInstance();
        cal.set(2008,10,02);
        actu.setDate(cal);
        actu.setResume("Avant d'essayer de comparer deux chaînes de caractères, il faut bien comprendre que l'opérateur '==' permet de comparer entre eux les types primitifs (int, float, boolean, etc. ) mais dans le cas des objets, cet opérateur compare les emplacements mémoire des objets : deux instances initialisées avec les mêmes paramètres occupent un espace mémoire différent, elles sont donc différentes du point de vue de '=='. L'opération qui permet de comparer les objets entre eux est la méthode equals() de java.lang.Object.\nLe JDK 1.4 vient un peu compliquer la chose en conservant une liste privée d'instances de String. Initialement, la liste est vide. L'appel de la méthode intern() cherche dans la liste si une instance est égale d'après 'equals()', si oui, cette instance est retournée, sinon la chaîne est ajoutée à la liste.");
        actu.setTitre("Comment comparer des chaînes de caractères ?");
        lstActu.add(actu);
 
        actu = new Actu();
        cal = Calendar.getInstance();
        cal.set(2008,10,12);
        actu.setDate(cal);
        actu.setResume("La conversion de chaînes de caractères en valeurs numériques est assurée par les différentes classes de gestion des types de base de Java : java.lang.Integer, java.lang.Double, java.lang.Float, java.lang.Long, java.lang.Byte. La chaîne ne doit contenir que le nombre à convertir : toute erreur lève l'exception java.lang.NumberFormatException.");
        actu.setTitre("Comment convertir une chaîne en nombre ?");
        lstActu.add(actu);
 
        actu = new Actu();
        cal = Calendar.getInstance();
        cal.set(2008,10,25);
        actu.setDate(cal);
        actu.setResume("Par défaut, la partie entière sera toujours agrandit même si le pattern précise un nombre d'élément moins important.\nA noter que toutes les caractéristiques du pattern peuvent être modifié par les méthodes de la classe DecimalFormat, et que la classe NumberFormat permet d'obtenir un certain nombre de formatage standard via des méthodes statiques.\nEnfin, à partir de Java 5.0 il est possible d'utiliser une syntaxe proche du printf() du C via la classe java.util.Formatter. Dans la pratique on n'utilisera pas directement cette classe mais des méthodes l'utilisant comme PrintStream.printf() ou String.format().\nCette syntaxe différencie les types entiers (short, int, long et BigInteger) des types réels (float, double et BigDecimal).");
        actu.setTitre("Comment convertir un nombre en chaîne formatée ?");
        lstActu.add(actu);
 
        actu = new Actu();
        cal = Calendar.getInstance();
        cal.set(2008,10,25);
        actu.setDate(cal);
        actu.setResume("La classe Integer dispose de 3 méthodes statiques permettant de convertir un entier décimal en une chaîne représentant son équivalent binaire, octal et hexadécimal. Afin d'obtenir la représentation dans la base de son choix d'un entier décimal, la classe Integer dispose des méthodes statiques toString().");
        actu.setTitre("Comment convertir un nombre entier décimal en une chaîne représentant ce nombre dans une autre base ?");
        lstActu.add(actu);
 
        return lstActu;
    }
 
    private List<String> formatStringForJava2d(String chaine, int nbcarLigne){
        List<String> retour = null;
        if(chaine!=null){
            List<String> lstChaine = new ArrayList<String>();
            List<String> lstResult = new ArrayList<String>();
            retour = new ArrayList<String>();
            if(chaine.contains("\n")){
                String[] tabChaine = chaine.split("\n");
                lstChaine.addAll(Arrays.asList(tabChaine));
            }else{
                lstChaine.add(chaine);
            }
            for(String ligne : lstChaine){
                if(ligne.length()<=nbcarLigne){
                    retour.add(ligne);
                }else{
                    while(ligne.length()>nbcarLigne){
                        ligne = ligne.trim();
                        int indexSpace = ligne.substring(0,nbcarLigne).lastIndexOf(' ');
                        if(indexSpace==-1){
                            //on ne peut pas couper la ligne proprement : pas d'espace du coup on coupe à la fin
                            indexSpace = nbcarLigne;
                        }
                        retour.add(ligne.substring(0,indexSpace));
                        ligne = ligne.substring(indexSpace).trim();
                    }
                    if(!ligne.equals("")){
                        retour.add(ligne);
                    }
                }
            }
        }
        return retour;
    }
}
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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
107
108
109
110
111
112
113
 
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
 
public class NewJDialog extends javax.swing.JDialog {
 
    /** Creates new form NewJDialog */
    public NewJDialog(java.awt.Frame parent, boolean modal)  {
        super(parent, modal);
        initComponents();
 
        actuJPanel1 = new ActuJPanel(this);
        jPanel1.add(actuJPanel1);
 
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                actuJPanel1.lanceDefile();
            }
        });  
    }
 
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                          
    private void initComponents() {
        jButton1 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });
 
        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
 
        jPanel1.setLayout(new javax.swing.BoxLayout(jPanel1, javax.swing.BoxLayout.LINE_AXIS));
 
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Actualit\u00e9s"));
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 301, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(108, 108, 108)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)))
                .addContainerGap())
        );
        pack();
    }// </editor-fold>                        
 
    private void formWindowClosing(java.awt.event.WindowEvent evt) {                                   
        System.exit(0);
    }                                  
 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
           actuJPanel1.lanceDefile();
    }                                        
 
    /**
     * @param args the command line arguments
     */
    public static void main(String args[])throws Exception {
 
        final NewJDialog jdialog  = new NewJDialog(new javax.swing.JFrame(), true);
        jdialog.pack();
        jdialog.setVisible(true);          
    }
 
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   
    private ActuJPanel actuJPanel1;
 
    public ActuJPanel getActuJPanel1(){
        return actuJPanel1;
    }
 
    public JButton getBouton(){
        return jButton1;
    }
 
 
}
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import javax.swing.SwingUtilities;
 
/**
 * This is the 3rd version of SwingWorker (also known as
 * SwingWorker 3), an abstract class that you subclass to
 * perform GUI-related work in a dedicated thread.  For
 * instructions on using this class, see:
 * 
 * http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
 *
 * Note that the API changed slightly in the 3rd version:
 * You must now invoke start() on the SwingWorker after
 * creating it.
 */
public abstract class SwingWorkerApo {
    private Object value;  // see getValue(), setValue()
    private Thread thread;
 
    /** 
     * Class to maintain reference to current worker thread
     * under separate synchronization control.
     */
    private static class ThreadVar {
        private Thread thread;
        ThreadVar(Thread t) { thread = t; }
        synchronized Thread get() { return thread; }
        synchronized void clear() { thread = null; }
    }
 
    private ThreadVar threadVar;
 
    /** 
     * Get the value produced by the worker thread, or null if it 
     * hasn't been constructed yet.
     */
    protected synchronized Object getValue() { 
        return value; 
    }
 
    /** 
     * Set the value produced by worker thread 
     */
    private synchronized void setValue(Object x) { 
        value = x; 
    }
 
    /** 
     * Compute the value to be returned by the <code>get</code> method. 
     */
    public abstract Object construct();
 
    /**
     * Called on the event dispatching thread (not on the worker thread)
     * after the <code>construct</code> method has returned.
     */
    public void finished() {
    }
 
    /**
     * A new method that interrupts the worker thread.  Call this method
     * to force the worker to stop what it's doing.
     */
    public void interrupt() {
        Thread t = threadVar.get();
        if (t != null) {
            t.interrupt();
        }
        threadVar.clear();
    }
 
    /**
     * Return the value created by the <code>construct</code> method.  
     * Returns null if either the constructing thread or the current
     * thread was interrupted before a value was produced.
     * 
     * @return the value created by the <code>construct</code> method
     */
    public Object get() {
        while (true) {  
            Thread t = threadVar.get();
            if (t == null) {
                return getValue();
            }
            try {
                t.join();
            }
            catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // propagate
                return null;
            }
        }
    }
 
 
    /**
     * Start a thread that will call the <code>construct</code> method
     * and then exit.
     */
    public SwingWorkerApo() {
        final Runnable doFinished = new Runnable() {
           public void run() { finished(); }
        };
 
        Runnable doConstruct = new Runnable() { 
            public void run() {
                try {
                    setValue(construct());
                }
                finally {
                    threadVar.clear();
                }
 
                SwingUtilities.invokeLater(doFinished);
            }
        };
 
        Thread t = new Thread(doConstruct);
        threadVar = new ThreadVar(t);
    }
 
    /**
     * Start the worker thread.
     */
    public void start() {
        Thread t = threadVar.get();
        if (t != null) {
            t.start();
        }
    }
}
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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
import java.util.Calendar;
 
public class Actu {
 
    /** Creates a new instance of Actu */
    public Actu() {
    }
 
    private String titre;
    private String resume;
    private Calendar date;
 
    public String getTitre() {
        return titre;
    }
 
    public void setTitre(String titre) {
        this.titre = titre;
    }
 
    public String getResume() {
        return resume;
    }
 
    public void setResume(String resume) {
        this.resume = resume;
    }
 
    public Calendar getDate() {
        return date;
    }
 
    public void setDate(Calendar date) {
        this.date = date;
    }
 
}