简体   繁体   English

使用文件更新 JList

[英]Updating a JList with Files

I'm trying to make a little program for a school project that extracts files.我正在尝试为一个提取文件的学校项目制作一个小程序。 I'm using a JList to display all the extracted files but after lots of hours lurking I can't figure out how to make this JList update when there are new files present in the folder.我正在使用 JList 来显示所有提取的文件,但是经过数小时的潜伏后,当文件夹中存在新文件时,我无法弄清楚如何更新此 JList。 It doesn't refresh properly in the button's ActionListener since the batch file (the actual extractor) takes a varied amount of time to finish.它没有在按钮的 ActionListener 中正确刷新,因为批处理文件(实际的提取器)需要不同的时间才能完成。 How can I get this to work?我怎样才能让它工作?

This is the class I'm using to find files of certain extension:这是我用来查找某些扩展名的文件的 class:

public class fileFinder {
    public static String[] thing() {
        File file = new File(".\\at9snfsbs");
        File[] files = file.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                if (name.toLowerCase().endsWith(".at9")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        String[] fileNames = new String[files.length];
        for (int i = 0; i < files.length; i++) {
            fileNames[i] = files[i].getName();
        }

        return fileNames;
    }

}

This is the JList:这是 JList:

        DefaultListModel model = new DefaultListModel();
        String[] things = fileFinder.thing();
        for (int i = 0; i < things.length; i++) {
            model.addElement(things[i]);
        }
        JList list = new JList(model);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        scrollPane.setViewportView(list);

And this is a button's ActionListener that starts a batch file which is the actual converter:这是一个按钮的 ActionListener,它启动一个批处理文件,它是实际的转换器:

try {
    Runtime.getRuntime().exec("cmd /c start .\\at9snfsbs\\shit.bat");
    String[] thang = fileFinder.thing();
    model.clear();
    for (int i = 0; i < thang.length; i++) {
        model.addElement(thang[i]);
    };
} catch (IOException e1) {
    e1.printStackTrace();
}

I'm not experienced or good in coding so any help would be appreciated!我在编码方面没有经验或擅长,所以任何帮助将不胜感激!

Andrew Thompson: See also When Runtime.exec() won't for many good tips on creating and handling a process correctly. Andrew Thompson:另请参阅When Runtime.exec() won't了解有关正确创建和处理进程的许多好技巧。 Then ignore it refers to exec and use a ProcessBuilder to create the process.然后忽略它指的是exec并使用ProcessBuilder来创建进程。 Also break a String arg into String[] args to account for things like paths containing space characters. String arg分解为String[] args以解决诸如包含空格字符的路径之类的问题。

I got it working with a ProcessBuilder and waitFor() .我让它与ProcessBuilderwaitFor()一起工作。

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

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