调用getter JFileChooser时出现NullPointerException

时间:2015-07-02 19:14:54

标签: java nullpointerexception getter jfilechooser

每次调用getter时,我都会收到NullPointerException。这是代码:

import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

public class FileChooser extends JFileChooser {
private int result;
private File filename;
private File subFile;
private FileNameExtensionFilter filter;

    public FileChooser() {
        filename = new File(System.getProperty("user.home"));
        filter = new FileNameExtensionFilter("Subtitle Files (*.srt)", "srt");
    }

    public void createAndShowGUI() {
        this.setDialogTitle("Select a file");
        this.setCurrentDirectory(filename);       
        this.setFileFilter(filter);
        result = this.showOpenDialog(this);
        if(result == JFileChooser.APPROVE_OPTION) 
            subFile = this.getSelectedFile();   
        this.setVisible(true);        
    }

    public File getFile() {
        return subFile;
    }

}

我使用调用getFile()函数的变量到处获取空指针。在这种情况下foo。这是片段:

FileChooser fileChooser = new FileChooser();
File foo = fileChooser.getFile();
System.out.println(foo.getName()); //Null-Pointer
System.out.println(foo.getPath()); //Null-Pointer  

更新:我碰巧有两个FileChooser个实例但是,我想只调用createAndShowGUI()一次。如何在构造函数中初始化所选文件?

4 个答案:

答案 0 :(得分:2)

嗯,你永远不会打电话给createAndShowGUI()。只需在致电getFile()

之前拨打电话

答案 1 :(得分:1)

根据您的代码,字段subFile已在createAndShowGUI()内的方法if condition中初始化。

但是,由于您没有调用方法createAndShowGUI(),因此当您致电subFile时,字段null仍为getFile()

试试这段代码,

FileChooser fileChooser = new FileChooser();
fileChooser.createAndShowGUI();             // MISSING IN ORIGINAL CODE
File foo = fileChooser.getFile();
System.out.println(foo.getName()); //Null-Pointer
System.out.println(foo.getPath()); //Null-Pointer

<强>更新

随着问题更新

  

我碰巧有两个FileChooser实例但是,我想只调用一次createAndShowGUI()

如果您只拨打一次createAndShowGUI(),那么用户只能选择一次该文件。

那么创建两个FileChooser实例的用途是什么?

每次创建createAndShowGUI()的新实例时,都需要致电FileChooser

答案 2 :(得分:1)

import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

public class FileChooser extends JFileChooser {
    private int result;
    private File filename;
    private File subFile;
    private FileNameExtensionFilter filter;

    public FileChooser() {
        filename = new File(System.getProperty("user.home"));
        filter = new FileNameExtensionFilter("Subtitle Files (*.srt)", "srt");
        this.setDialogTitle("Select a file");
        this.setCurrentDirectory(filename);       
        this.setFileFilter(filter);
        result = this.showOpenDialog(this);
        if(result == JFileChooser.APPROVE_OPTION) 
            subFile = this.getSelectedFile();   
        this.setVisible(true);
    }

    public File getFile() {
        return subFile;
    }

}

答案 3 :(得分:0)

我认为这是个问题:

if(result == JFileChooser.APPROVE_OPTION) 
        subFile = this.getSelectedFile();  

result == JFileChooser.APPROVE_OPTION返回false,subFile从未初始化