I'm getting a NullPointerException every time I call a getter. Here's the code:
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;
}
}
I get null pointer everywhere I use the variable that calls the getFile()
function. foo
in this case. Here's the snippet:
FileChooser fileChooser = new FileChooser();
File foo = fileChooser.getFile();
System.out.println(foo.getName()); //Null-Pointer
System.out.println(foo.getPath()); //Null-Pointer
UPDATE: I happen to have two instances of FileChooser
but, I would like to call createAndShowGUI()
only once. How do I initialise the selected file in the constructor ?