我正在尝试显示我在 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
,但它没有在界面中显示列表。
根据您可用的上下文外代码,显而易见的答案是,您实际上没有向 UI 添加jScrollCortes
......
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();
//...
}
这可能有效,也可能无效,具体取决于类、UI 和/或布局的设置方式。
更好的解决方案是在UI上显示JList
和JScrollPane
已经创建的内容,然后您需要做的就是将新ListModel
应用于现有的JList
当我从 Swing Controls Palette 添加 JList 时,JScrollPane 默认创建,我将其名称更改为 jScrollCortes
由于您已经有一个JList
实例(包装在JScrollPane
中(,那么您应该只需要更改模型......
DefaultListModel model = new DefaultListModel();
//...
// Add the JList to the JScrollPane
jCortesList.setModel(model);
//jCortesList = new JList(model);
//jScrollCortes = new JScrollPane(jCortesList);