Bonjour,
J'ai un petit programme simple ci-dessous dans lequel j'ai inséré un objet JFileChooser. Je ne sais pourquoi, le fichier sélectionné (objet file) est NULLL en retour de méthode :

int returnVal = fchooser.showOpenDialog(this.createComponents());
if (returnVal == JFileChooser.APPROVE_OPTION) {
fchooser.approveSelection();
File file = fchooser.getSelectedFile ();

alors que 'jai récupéré ce code dans bcp d'exemples. Est-ce le bout de code
this.createComponents()
qui pose probleme ?

Quelqu'un a-t-il une idée ?

Merci


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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/*
 * Créé le 8 août 07
 *
 * Pour changer le modèle de ce fichier généré, allez à :
 * Fenêtre>Préférences>Java>Génération de code>Code et commentaires
 */
package examples;
 
/*
 * SwingApplication.java is a 1.4 example that requires
 * no other files.
 */
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
 
import javax.swing.DefaultListModel;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.TitledBorder;
 
public class SwingApplication implements ActionListener { 
 
     private static Button bouton_selectionner, bouton_valider, bouton_ajouter, bouton_supprimer;
 
     private static String listeDiffusion; 
     private JTextField nameField;
     private JTextArea log; 
     private JFileChooser fchooser;
 
     // Declatation des pannels
     ////////////////////////////
     private static JPanel panel_liste=new JPanel();
     private static JPanel panel_type=new JPanel();
     private static JPanel panel_bouton=new JPanel();
     private static JComboBox comboBox = new JComboBox();
 
     private static JList liste, listeHabilitation, listeProfil  ;
     private static DefaultListModel listModel, listModelHabilitation, listModelProfil; 
 
     private static JPanel panel_general=new JPanel();
 
    //Specify the look and feel to use.  Valid values:
    //null (use the default), "Metal", "System", "Motif", "GTK+" 
    final static String LOOKANDFEEL = null;
 
    public Component createComponents() {
 
        bouton_selectionner    =    new Button("Selectionner..");
        bouton_valider    =    new Button("Valider"); 
        bouton_ajouter     =     new Button("ajouter");
        bouton_supprimer =     new Button("supprimer");    
 
        fchooser = new JFileChooser();
 
        listeDiffusion = ""; 
 
        ////////////////////
        // LOGS
        log = new JTextArea(10, 30);
        JScrollPane logScrollPane = new JScrollPane(log);
        logScrollPane.setBorder(new TitledBorder("Console")); 
       // initialiser();
 
        // Affectation d'un titre au panel
        //Liste
        panel_liste.setBorder(new TitledBorder("Listes de diffusions"));
        listModel = new DefaultListModel(); 
        listModel.addElement("Internet Explorer..test....");
        listModel.addElement("Netscape");
        listModel.addElement("Mozilla");
        listModel.addElement("firefox"); 
 
        // Traitements 1ere liste.
        ///////////////////////////
        liste = new JList(listModel);
        liste.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        liste.setLayoutOrientation (JList.VERTICAL);
        liste.setSize(80,40);
        liste.addMouseListener(new MouseAdapter() {
 
                public void mousePressed(MouseEvent e) {
 
 
                        // Traitement évenement clic sur la 1ere liste 
                        int index = liste.getSelectedIndex();
                        if (index != -1) {
                                int size = listModel.getSize();
                                String valeur = (String) listModel.elementAt(index);
                                log.append(" 1 : click :" + valeur + "\n");
 
 
                                // Effacement des listes 2 et 3
                                listModelHabilitation.clear();
                                listModelProfil.clear();
 
                                listModelHabilitation.addElement(valeur);
                                listModelHabilitation.addElement (valeur + "1");
                                bouton_valider.setEnabled(false);
                        }
                }
        });
 
        // Traitement 2eme liste
        //////////////////////////// 
        listModelHabilitation = new DefaultListModel();
        listeHabilitation = new JList(listModelHabilitation);
        listeHabilitation.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        listeHabilitation.setLayoutOrientation(JList.VERTICAL);
        listeHabilitation.addMouseListener(new MouseAdapter() {
 
                public void mousePressed(MouseEvent e) {
 
                        // Traitement éenement click sur la 2nd liste 
 
                        int index = listeHabilitation.getSelectedIndex();
                        if (index != -1) {
 
                                int size = listModelHabilitation.getSize();
 
                                // Effacement des listes 2 et 3 
                                listModelProfil.clear();
 
                                String valeur = (String) listModelHabilitation.elementAt(index);
                                log.append(" 2 : click :" + valeur + "\n"); 
                                listModelProfil.addElement(valeur);
                                listModelProfil.addElement(valeur + "2");
                                bouton_valider.setEnabled(false); 
 
                        }
                                }
        });
 
        // Traitements 3eme liste
        /////////////////////////////
        listModelProfil = new DefaultListModel();
        listeProfil = new JList(listModelProfil);
        listeProfil.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        listeProfil.setLayoutOrientation(JList.VERTICAL);
 
        listeProfil.addMouseListener (new MouseAdapter(){
 
                public void mousePressed(MouseEvent e) {
 
                        // Traitement évenement click sur la 3eme liste
 
                        int index = listeProfil.getSelectedIndex ();
                        if (index != -1) {
 
                                bouton_valider.setEnabled(true);
 
                        } else {
                                bouton_valider.setEnabled(false); 
                        }
                }
 
        });
 
        // Ajout au panel "Liste"
        ////////////////////////////
        panel_liste.add(new JLabel("Navigateurs")); 
        panel_liste.add(new JScrollPane(liste));
 
        panel_liste.add(new JScrollPane(listeHabilitation));
        panel_liste.add(new JScrollPane(listeProfil));
 
        // Ajout des boutons au panel "boutons" 
        ///////////////////////////////////////
        panel_bouton.setBorder(new TitledBorder("actions"));
        panel_bouton.add(bouton_selectionner);
        panel_bouton.add(bouton_valider);
        panel_bouton.add(bouton_ajouter);
        panel_bouton.add(bouton_supprimer);
 
        // Ajout des panels au panel "general"
        panel_general.setLayout(new BorderLayout());
        panel_general.add(panel_liste, BorderLayout.NORTH);
        panel_general.add(panel_type, BorderLayout.WEST);
        panel_general.add(panel_bouton, BorderLayout.EAST);        
        panel_general.add(logScrollPane, BorderLayout.CENTER);
 
        bouton_valider.addActionListener(this);
        bouton_valider.setEnabled(false);
 
        bouton_ajouter.addActionListener(this);
        bouton_supprimer.addActionListener(this);
        bouton_selectionner.addActionListener(this); 
 
        liste.setFixedCellWidth(150);
        listeHabilitation.setFixedCellWidth(150);
        listeProfil.setFixedCellWidth(150);
 
        liste.setFixedCellHeight(15);
        listeHabilitation.setFixedCellHeight(15);
        listeProfil.setFixedCellHeight(15);
        ////////////////////
        /*
         * An easy way to put space between a top-level container
         * and its contents is to put the contents in a JPanel
         * that has an "empty" border. 
         */
 
        /*panel_general.setBorder(BorderFactory.createMatteBorder(
                30, //top
                30, //left
                10, //bottom
                30, //right
                Color.lightGray));
       */
        return panel_general;
    }
   /**
    * 
    */
    public void actionPerformed(ActionEvent e) {
        String test="test";
 
 
        if (e.getSource() == bouton_ajouter) {
 
                log.append(" actionPerformed.bouton_ajouter\n");
        }
 
        if (e.getSource() == bouton_selectionner) {
 
            log.append (" avant showdialog\n");
            int returnVal = fchooser.showOpenDialog(this.createComponents());
             if (returnVal == JFileChooser.APPROVE_OPTION) {
            	 fchooser.approveSelection();
                 File file = fchooser.getSelectedFile ();
                 //This is where a real application would open the file.
                 log.append("Opening: " + file.getName() + "." + "\n");
             } else {
                 log.append("Open command cancelled by user." + "\n");
             }
             log.setCaretPosition(log.getDocument().getLength());
 
                log.append(" actionPerformed.bouton_supprimer\n ");
        }
 
        if (e.getSource() == bouton_valider) {
 
            // Envoi d'emails aux listes de diffusion.
            String domaine = (String) listModel.elementAt(liste.getSelectedIndex ());
            String application = (String) listModelHabilitation.elementAt(listeHabilitation.getSelectedIndex());
            String profil = (String) listModelProfil.elementAt(listeProfil.getSelectedIndex());
 
            log.append(" actionPerformed.bouton_valider : " + domaine + "." + application + "." + profil + "\n");
    }
}
 
   /**
    * 
    *
    */
    private static void initLookAndFeel() {
 
        // Swing allows you to specify which look and feel your program uses--Java,
        // GTK+, Windows, and so on as shown below.
        String lookAndFeel = null; 
 
        if (LOOKANDFEEL != null) {
            if (LOOKANDFEEL.equals("Metal")) {
                lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName();
            } else if (LOOKANDFEEL.equals ("System")) {
                lookAndFeel = UIManager.getSystemLookAndFeelClassName();
            } else if (LOOKANDFEEL.equals("Motif")) {
                lookAndFeel = "com.sun.java.swing.plaf.motif.MotifLookAndFeel ";
            } else if (LOOKANDFEEL.equals("GTK+")) { //new in 1.4.2
                lookAndFeel = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
            } else {
                System.err.println("Unexpected value of LOOKANDFEEL specified: "
                        + LOOKANDFEEL);
                lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName();
            }
 
            try {
                UIManager.setLookAndFeel(lookAndFeel);
            } catch (ClassNotFoundException e) {
                System.err.println("Couldn't find class for specified look and feel:" 
                        + lookAndFeel);
                System.err.println("Did you include the L&F library in the class path?");
                System.err.println("Using the default look and feel."); 
            } catch (UnsupportedLookAndFeelException e) {
                System.err.println("Can't use the specified look and feel ("
                        + lookAndFeel
                        + ") on this platform."); 
                System.err.println("Using the default look and feel.");
            } catch (Exception e) {
                System.err.println("Couldn't get specified look and feel ("
                        + lookAndFeel
                        + "), for some reason.");
                System.err.println("Using the default look and feel.");
                e.printStackTrace ();
            }
        }
    }
 
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() { 
        //Set the look and feel.
        initLookAndFeel();
 
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);
 
        //Create and set up the window. 
        JFrame frame = new JFrame("SwingApplication");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        SwingApplication app = new SwingApplication();
        Component contents = app.createComponents();
        frame.getContentPane().add(contents, BorderLayout.CENTER);
 
        //Display the window.
        frame.pack();
        //frame.getContentPane().setLayout(new GridLayout(2, 3)); 
        //frame.setSize(850,500);
        //frame.setResizable(false);
        frame.setVisible(true);
    }
 
    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread: 
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}