I have a set of files in a folder, and all of them starting with a similar name pattern. Here is an example:
Spectrum_1.txt
Spectrum_2.txt
Spectrum_3.txt
....
....
....
Spectrum_10.txt
Spectrum_11.txt
....
....
....
Spectrum_20.txt
....
....
....
I am able to list all the files from the specified folder, but the list is not in an ascending order of the spectrum number. I have a sort method which could correct this:
public class SortFile {
/**
* Method which takes list of files as a fileArray and sorts them
*
* @param File[] files
* @return File[] files
*/
public File[] sortByNumber(File[] files) {
Arrays.sort(files, new Comparator<File>() {
//@Override
public int compare(File o1, File o2) {
int n1 = extractNumber(o1.getName());
int n2 = extractNumber(o2.getName());
return n1 - n2;
}
private int extractNumber(String name) {
int i = 0;
try {
int s = name.indexOf('_')+1;
int e = name.lastIndexOf('.');
String number = name.substring(s, e);
i = Integer.parseInt(number);
} catch(Exception e) {
i = 0; // if filename does not match the format
// then default to 0
}
return i;
}
});
return files;
}
}
But, I am not sure how to get it working with the JTree code:
public void actionPerformed(ActionEvent e) {
//Handle open button action.
if (e.getSource() == OpenFileButton) {
int returnVal = fc.showOpenDialog(GUIMain.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
File[] filesInDirectory = file.listFiles();
SortFile sf = new SortFile();
// Calls sortByNumber method in class SortFile to list the files number wise
filesInDirectory = sf.sortByNumber(filesInDirectory);
// Jtree takes the File datatype as input
tree = new JTree(addNodes(null, file));
// Add a listener
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) e
.getPath().getLastPathComponent();
System.out.println("You selected " + node);
}
});
spectralFilesScrollPane = new JScrollPane();
spectralFilesScrollPane.getViewport().add(tree);
spectralFilesScrollPane.setPreferredSize(new Dimension(290, 465));
content.add(spectralFilesScrollPane);
// // content.invalidate();
content.validate();
content.repaint();
}
}
}
The problem I am facing is, the sort method returns an array of files and the JTree is using the File datatype. How can I resolve this?
Solved the problem by making changes into the addNodes method.