Trying to Add a list of files to a Jlist, then filter the files in the JList to only return .txt files and fixed char length. Also trying remove the file path that gets returned, and only show the filename+extension in the JList of files.
So far, accomplished all except removing the file path. For example, it still returns "C:\java_help.txt" instead of just "java_help.txt" in the JList.
import javax.swing.*;
import java.io.*;
public class FileName extends JFrame{
JPanel pnl=new JPanel();
public static void main (String[]args) {
FileName print=new FileName();
}
JList list;
@SuppressWarnings("unchecked")
public FileName() {
super("Swing Window");
setSize(250,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
add(pnl);
String path="C:/";
File folder=new File(path);
File[]listOfFiles=folder.listFiles(new TextFileFilter());
list=new JList(listOfFiles);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setLayoutOrientation(JList.VERTICAL);
pnl.add(list);
pnl.revalidate();
}
}
class TextFileFilter implements FileFilter {
public boolean accept(File file) {
String name=file.getName();
return name.length()<28&&name.endsWith(".txt");
}
}
I thought getName() was supposed to accomplish this, but it doesn't seem to be the case. How can I remove the path from the filename, and be left with just filename+extension in the JList? Applicable examples to the code above would be appreciated.