JList that contains the list of Files in a directory
I created a JList
that contains a list of files that are in a directory.
Here is the JList
.
JList MList;
String ListData[]
// Create a new listbox control
List = new JList(ListData);
I also crea开发者_运维问答ted a method that reads a list of text files in a directory:
public String ReadDirectory() {
String path = "C://Documents and Settings/myfileTxt";
String files = null;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT")) {
System.out.println(files);
}
}
}
return files;
}
The problem is I want the result of this method (the list of text files) in a JList
.
How can I put the File
objects in the JList
?
Don't put strings into the JList
, use File
objects and set a renderer. Since the component returned by the default renderer is a JLabel
, it is easy to set an icon.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.Border;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.FileFilter;
/**
This code uses a JList in two forms (layout orientation vertical & horizontal wrap) to
display a File[]. The renderer displays the file icon obtained from FileSystemView.
*/
class FileList {
public Component getGui(File[] all, boolean vertical) {
// put File objects in the list..
JList fileList = new JList(all);
// ..then use a renderer
fileList.setCellRenderer(new FileRenderer(!vertical));
if (!vertical) {
fileList.setLayoutOrientation(javax.swing.JList.HORIZONTAL_WRAP);
fileList.setVisibleRowCount(-1);
} else {
fileList.setVisibleRowCount(9);
}
return new JScrollPane(fileList);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
File f = new File(System.getProperty("user.home"));
FileList fl = new FileList();
Component c1 = fl.getGui(f.listFiles(new TextFileFilter()),true);
//f = new File(System.getProperty("user.home"));
Component c2 = fl.getGui(f.listFiles(new TextFileFilter()),false);
JFrame frame = new JFrame("File List");
JPanel gui = new JPanel(new BorderLayout());
gui.add(c1,BorderLayout.WEST);
gui.add(c2,BorderLayout.CENTER);
c2.setPreferredSize(new Dimension(375,100));
gui.setBorder(new EmptyBorder(3,3,3,3));
frame.setContentPane(gui);
frame.pack();
frame.setLocationByPlatform(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class TextFileFilter implements FileFilter {
public boolean accept(File file) {
// implement the logic to select files here..
String name = file.getName().toLowerCase();
//return name.endsWith(".java") || name.endsWith(".class");
return name.length()<20;
}
}
class FileRenderer extends DefaultListCellRenderer {
private boolean pad;
private Border padBorder = new EmptyBorder(3,3,3,3);
FileRenderer(boolean pad) {
this.pad = pad;
}
@Override
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
Component c = super.getListCellRendererComponent(
list,value,index,isSelected,cellHasFocus);
JLabel l = (JLabel)c;
File f = (File)value;
l.setText(f.getName());
l.setIcon(FileSystemView.getFileSystemView().getSystemIcon(f));
if (pad) {
l.setBorder(padBorder);
}
return l;
}
}
@Andrew Thompson
eeeergght nothing good coming from this night 03:36AM in my TimeZone and at 06:00 I must wakeUp,
but somewhere I lost (not me) JLabel, heavens where it could be
import java.awt.*;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
public class FilesInTheJList {
public FilesInTheJList() {
JList displayList = new JList(new File("C:\\").listFiles());
displayList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
displayList.setCellRenderer(new MyCellRenderer());
displayList.setLayoutOrientation(javax.swing.JList.HORIZONTAL_WRAP);
displayList.setName("displayList");
JFrame f = new JFrame("Files In the JList");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(500, 300));
displayList.setVisibleRowCount(-1);
f.add(new JScrollPane(displayList));
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
FilesInTheJList fITJL = new FilesInTheJList();
}
});
}
private static class MyCellRenderer extends DefaultListCellRenderer {
private static final long serialVersionUID = 1L;
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (value instanceof File) {
File file = (File) value;
setText(file.getName());
setIcon(FileSystemView.getFileSystemView().getSystemIcon(file));
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
setEnabled(list.isEnabled());
setFont(list.getFont());
setOpaque(true);
}
return this;
}
}
}
import java.awt.*;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
public class FilesInTheJList {
private static final int COLUMNS = 4;
private Dimension size;
public FilesInTheJList() {
final JList list = new JList(new File("C:\\").listFiles()) {
private static final long serialVersionUID = 1L;
@Override
public Dimension getPreferredScrollableViewportSize() {
if (size != null) {
return new Dimension(size);
}
return super.getPreferredScrollableViewportSize();
}
};
list.setFixedCellHeight(50);
list.setFixedCellWidth(150);
size = list.getPreferredScrollableViewportSize();
size.width *= COLUMNS;
list.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
list.setCellRenderer(new MyCellRenderer());
list.setVisibleRowCount(0);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
JFrame f = new JFrame("Files In the JList");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(list));
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
FilesInTheJList fITJL = new FilesInTheJList();
}
});
}
private static class MyCellRenderer extends JLabel implements ListCellRenderer {
private static final long serialVersionUID = 1L;
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (value instanceof File) {
File file = (File) value;
setText(file.getName());
setIcon(FileSystemView.getFileSystemView().getSystemIcon(file));
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
setPreferredSize(new Dimension(250, 25));
setEnabled(list.isEnabled());
setFont(list.getFont());
setOpaque(true);
}
return this;
}
}
}
I don't quite understand what you're doing - it looks like you want to filter the content of the JList to be only files with the .txt
extension. In that case, you're probably looking to implement a FilenameFilter
that will cause list()
to return a list of file names in a String[]
that only matches what you specified.
For example,
public String[] ReadDirectory() {
String path = "C://Documents and Settings/myfileTxt";
String files = null;
File folder = new File(path);
FilenameFilter txtFilter = new TextFileFilter();
String[] listOfFiles = folder.listFiles(txtFilter);
return listOfFiles;
}
public class TextFileFilter extends FilenameFilter
{
public boolean accept(File dir, String name)
{
if(name != null && name.endsWith(".txt"))
{
return true;
}
return false;
}
}
Create list of strings List<String> fnames = new ArrayList<String>();
, fill it with file names (fnames.add(files);
), then set it to JList using list.setListData(fnames.toArray());
. I guess that should work.
Just edit your code like this,
public ArrayList<String> ReadDirectory() {
String path = "C://Documents and Settings/myfileTxt";
ArrayList<String> files = new ArrayList<String>();
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files.add(listOfFiles[i].getName());
if (files.endsWith(".txt") || files.endsWith(".TXT")) {
System.out.println(files);
}
}
}
return files;
}
Which will return ArrayList object and then you can convert that ArrayList object to a normal array.
Something like this, Lets say your variable name is,
ArrayList<String> listData = new ArrayList<String>();
Just do this to convert it into normal array,
listData.toArray();
精彩评论