I'm trying to display a list of files that I get of a folder in a JList, this is my code but when I run the project and select the desired folder I obtain the names of the files in the Output console but I can't show that File[] array in the JList.
private void jButtonOpenActionPerformed(java.awt.event.ActionEvent evt) {
// Gets the path of the folder selected
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setCurrentDirectory(new File("C:\\...\\ProjectColorCT"));
int show_fileC = fileChooser.showOpenDialog(this);
String pathFolder = null;
if (show_fileC != JFileChooser.CANCEL_OPTION ){
File folderName = fileChooser.getSelectedFile();
pathFolder = folderName.getAbsolutePath();
jTextPathFolder.setText(pathFolder);
}
System.out.println(pathFolder);
// Gets all the names of the files inside the folder selected previously
File folderCortes = new File(pathFolder);
File[] archivos = folderCortes.listFiles();
for (File fichero : archivos) {
System.out.println(fichero.getName());
}
// Create the model for the JList
DefaultListModel model = new DefaultListModel();
// Add all the elements of the array "archivos" in the model
for (int i=0 ; i<archivos.length ; i++){
model.addElement(archivos[i].getName());
}
// Add the JList to the JScrollPane
jCortesList = new JList(model);
jScrollCortes = new JScrollPane(jCortesList);
// Print for testing
for (int i=0 ; i<archivos.length ; i++){
jCortesList.setSelectedIndex(i);
System.out.println(jCortesList.getSelectedValue());
}
}
I'm adding a DefaultListModel();
and after I assign that model to the JList
, finally I assign that JList
to the JScrollPane
, but it doesn't show me the list in the interface.
答案 0 :(得分:0)
Based on your available, out-of-context code, the obvious answer would be, you've not actually added jScrollCortes
to the UI...
private void jButtonOpenActionPerformed(java.awt.event.ActionEvent evt) {
//...
// Add the JList to the JScrollPane
jCortesList = new JList(model);
jScrollCortes = new JScrollPane(jCortesList);
add(jScrollCortes);
revalidate();
repaint();
//...
}
This may or may not work depending on how the classes, UI and/or layout is setup.
A better solution would be to have the JList
and JScrollPane
already created an displayed on the UI, then all you'd need to do is apply the new ListModel
to the already existing JList
When I add the JList from the Swing Controls Palette the JScrollPane creates by default and I changed it the name to jScrollCortes
Since you already have an instance of JList
(wrapped in a JScrollPane
), then you should simply only need to change the model...
DefaultListModel model = new DefaultListModel();
//...
// Add the JList to the JScrollPane
jCortesList.setModel(model);
//jCortesList = new JList(model);
//jScrollCortes = new JScrollPane(jCortesList);