user3155369
user3155369

Reputation: 15

Java: list of files in jlist showing filename+extension only

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.

Upvotes: 1

Views: 3106

Answers (6)

kHAN
kHAN

Reputation: 1

Here's a simple implementation of the ListCellRenderer wolfcastle suggests that will do what you want:

class SimpleFileCellRenderer extends DefaultListCellRenderer implements ListCellRenderer<Object>
{
    // Use this to show relative paths instead of absolute.  
    @Override
    public Component getListCellRendererComponent(
            JList<? extends Object> list, Object value, int index,
            boolean isSelected, boolean cellHasFocus) {

        Path relative = ((File) value).toPath().getFileName();

        return super.getListCellRendererComponent(list, relative, index, isSelected, cellHasFocus);
    }
}

Just call JList.setCellRenderer(new SimpleFileCellRenderer()); and you should be set.

Upvotes: 0

wolfcastle
wolfcastle

Reputation: 5930

I think the problem here isn't the code you have: the file filter looks okay. I think your complaint is how the text is displayed in the JList.

You need to implement a ListCellRender to change the display text.

See the JList tutorial for how to do this.

Upvotes: 1

Paul Samsotha
Paul Samsotha

Reputation: 208984

This works, but you only get the String and not the File object. Note if you replace the "C:\", the File path will no longer be valid if you need to retrieve the File object. So instead you just have a list of file names instead of File objects. That may be a reason the "C:\" stays in there originally.

String path = "C:/";
File folder = new File(path);
File[] listOfFiles = folder.listFiles(new TextFileFilter());

List<String> fileNames = new ArrayList<String>();
for (File f: listOfFiles) {
fileNames.add(f.getName().replace(path, ""));
}

list = new JList(fileNames.toArray());

Upvotes: 0

SnakeDoc
SnakeDoc

Reputation: 14361

The problem is your method accept() in TextFileFilter class.

Something is wrong with your return line, and I'm not entirely sure what you were trying to do there. It appears you are trying to return the name.

for me, this works as expected:

import java.io.File;

public class Test {
    public static void main(String[] args) {
        File f = new File("C:\\bell.wav");
        System.out.println(f.getName());
    }
}

Prints: bell.wav

If File is not working for you, try using Paths instead.

import java.nio.file.Path;
import java.nio.file.Paths;

public class Test {
    public static void main(String[] args) {
        Path p = Paths.get("C:\\bell.wav");
        System.out.println(p.getFileName());
    }
}

Prints: bell.wav

Upvotes: 0

ashes999
ashes999

Reputation: 10163

Since you used 'C:` in your path, I assume you're on Windows and want something that will work on Windows.

Just trim the path:

String name=file.getName();
name = name.substring(name.lastIndexOf('\\'));
// ...

This will delete the path, leaving you with only the filename.

Obviously, it won't work on Linux. If you need it to, you can switch the character you're looking for. On Windows, this works.

Upvotes: 0

Spencer D
Spencer D

Reputation: 3486

take the returned value and do

String[] PartsOfPath = ReturnedPath.split("\");

String JustFileName = PartsOfPath[(PartsOfPath.length - 1)];

I haven't tested that, but I would think that should work. Obviously swap with the variables names you need.

Upvotes: 0

Related Questions