【发布时间】:2018-05-09 02:45:59
【问题描述】:
我正在尝试显示从 JList 中的文件夹获取的文件列表,这是我的代码,但是当我运行项目并选择所需的文件夹时,我会在输出控制台中获得文件的名称,但是我无法在 JList 中显示 File[] 数组。
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());
}
}
我添加了一个DefaultListModel();,在我将该模型分配给JList 之后,最后我将JList 分配给JScrollPane,但它没有在界面中显示列表。
【问题讨论】:
-
jScrollCortes何时添加到 UI 中? -
当我从 Swing Controls Palette 添加
JList时,JScrollPane默认创建,我将其名称更改为 jScrollCortes