尝试将文件加载到JList时出现意外错误

时间:2014-12-16 06:42:03

标签: java swing file nullpointerexception

我正在尝试为基于unix的系统构建基于Java的网络管理器,但我遇到了一些麻烦,我找不到源代码:

Exception in thread "main" java.lang.NullPointerException
    at net.argvarg.NetworkManual.SelectConfDialog.loadConfList(SelectConfDialog.java:51)
    at net.argvarg.NetworkManual.SelectConfDialog.<init>(SelectConfDialog.java:20)
    at net.argvarg.NetworkManual.Main.run(Main.java:16)
    at net.argvarg.NetworkManual.Main.main(Main.java:7)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

以下是发出错误的文件部分:

package net.argvarg.NetworkManual;

import javax.swing.*;
import java.awt.event.*;
import java.io.File;

public class SelectConfDialog extends JDialog {

    private DefaultListModel confList = new DefaultListModel();
    private JList confListContainer = new JList(confList);
    private File[] confs = new File(Main.absolutePathToConfsDir).listFiles();

    private void loadConfList() {
        for (int i = 0; i < confs.length - 1; i++) {
            confList.addElement(confs[i].getName());
        }
    }
}

非常感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:1)

基于上面的评论,这里有一些很好的解决方案

 private void loadConfList() {
        if(confs == null || confs.length == 0){
                confList.addElement("Failed To Load Conf.");
                return;
        }//confs == null | empty

        for (int i = 0; i < confs.length - 1; i++) {
            confList.addElement(confs[i].getName());
        }
    }//loadConfList()

归功于@MadProgrammer,如果他发布了答案,则标记他的。