我有一个如下所示创建的JFileChooser:
JFileChooser chooser = new JFileChooser();
int choosen = chooser.showOpenDialog(fileSelector.this);
if (choosen == JFileChooser.CANCEL_OPTION) {
System.out.println("Closed");
}
如果我在没有做出选择的情况下关闭窗口,我会收到错误:
Exception in thread "main" java.lang.NullPointerException
at fileSelector.fileSelector(fileSelector.java:32)
at createAndControl.main(createAndControl.java:15)
我想知道处理这个问题的正确方法是什么,我应该在关闭窗口时调用什么操作来避免这种情况?
TIA
答案 0 :(得分:2)
建议反过来这样做:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
System.out.println("Opening: " + file.getName() + ".\n");
} else {
System.out.println("Open command cancelled by user.\n");
}
}
});
}