简体   繁体   English

Java:jlist中的文件列表仅显示文件名和扩展名

[英]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. 尝试将文件列表添加到Jlist中,然后过滤JList中的文件以仅返回.txt文件和固定的字符长度。 Also trying remove the file path that gets returned, and only show the filename+extension in the JList of files. 也尝试删除返回的文件路径,并且仅在文件的JList中显示filename +扩展名。

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. 例如,它仍然返回“ C:\\ java_help.txt”,而不是JList中的“ java_help.txt”。

    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. 我以为getName()应该可以做到这一点,但事实并非如此。 How can I remove the path from the filename, and be left with just filename+extension in the JList? 如何从文件名中删除路径,而在JList中仅保留文件名和扩展名? Applicable examples to the code above would be appreciated. 上面代码的适用示例将不胜感激。

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 . 我认为您的抱怨是如何在JList显示文本。

You need to implement a ListCellRender to change the display text. 您需要实现一个ListCellRender来更改显示文本。

See the JList tutorial for how to do this. 有关如何执行此操作,请参见JList教程

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. 显然与您需要的变量名称交换。

Since you used 'C:` in your path, I assume you're on Windows and want something that will work on Windows. 由于您在路径中使用了“ C:”,因此我假设您使用的是Windows,并且想要在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. 显然,它在Linux上不起作用。 If you need it to, you can switch the character you're looking for. 如果需要,您可以切换要查找的字符。 On Windows, this works. 在Windows上,这有效。

The problem is your method accept() in TextFileFilter class. 问题是您的TextFileFilter类中的方法accept()

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 印刷品:bell.wav

If File is not working for you, try using Paths instead. 如果File对您不起作用,请尝试使用Paths

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 印刷品:bell.wav

This works, but you only get the String and not the File object. 这可行,但是您只会得到String而不是File对象。 Note if you replace the "C:\\", the File path will no longer be valid if you need to retrieve the File object. 请注意,如果替换“ C:\\”,则如果需要检索File对象,则File路径将不再有效。 So instead you just have a list of file names instead of File objects. 因此,您只拥有一个文件名列表,而不是File对象。 That may be a reason the "C:\\" stays in there originally. 这可能是“ C:\\”最初停留在此的原因。

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());

Here's a simple implementation of the ListCellRenderer wolfcastle suggests that will do what you want: 这是ListCellRenderer wolfcastle的一个简单实现,建议您执行所需的操作:

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()); 只需调用JList.setCellRenderer(new SimpleFileCellRenderer()); and you should be set. 并且应该被设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM