2011-12-01 141 views
0

我有一个创建如图所示一个JFileChooser:处理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

什么线是造成异常? – unholysampler

+0

什么是fileselector.java第32行?如果你喜欢,可以参考JFileChooser上的[tutorial](http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html) - 它有一些很好的代码示例。 – aishwarya

+0

我试过你的代码,它工作。正如其他人所说的,更多的代码会很好。 – Anthea

回答

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"); 
      } 
     } 
    }); 
}