显示默认目录中的所有文件名
import java.awt.BorderLayout;..
import javax.swing.JScrollPane;
public class FileList extends JFrame{
private static final String FILES_DIR = "audio";
private JList fileList;
public FileList(){
super("FileList");
String[] fileNames = findFiles(FILES_DIR, null);
makeFrame(fileNames);
// TODO Auto-generated constructor stub
}
private void makeFrame(String[] autoNames) {
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel contentPane = (JPanel)getContentPane();
fileList = new JList(autoNames);
fileList.setForeground(new Color(140,171,226));
fileList.setBackground(new Color(0,0,0));
fileList.setSelectionBackground(new Color(87,49,134));
fileList.setSelectionForeground(new Color(140,171,226));
JScrollPane scrollPane = new JScrollPane(fileList);
scrollPane.setColumnHeaderView(new JLabel("files list"));
contentPane.add(scrollPane, BorderLayout.CENTER);
pack();
// place this frame at the center of the screen and show
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
setLocation(d.width/2 - getWidth()/2, d.height/2 - getHeight()/2);
setVisible(true);
}
private String[] findFiles(String dirName, String suffix) {
File dir = new File(dirName);
if(dir.isDirectory()) {
String[] allFiles = dir.list();
if(suffix == null) {
return allFiles;
}
else {
List<String> selected = new ArrayList<String>();
for(String filename : allFiles) {
if(filename.endsWith(suffix)) {
selected.add(filename);
}
}
return selected.toArray(new String[selected.size()]);
}
}
else {
System.out.println("Error: " + dirName + " must be a directory");
return null;
}
}
/**
* @param args
*/
public static void main(String[] args) {
new FileList();
}
}