public void openDialog() {
        chooser.setCurrentDirectory(new File("."));
        // 文件过滤
        chooser.setFileFilter(new FileFilter() {
            public boolean accept(File f) {
                String fileName = f.getName().toLowerCase();
                return fileName.endsWith(".txt") || f.isDirectory();
            }
            public String getDescription() {
                return "Text Files";
            }
        });
        int openResult = chooser.showOpenDialog(MainWindow.this);
        if (openResult == JFileChooser.APPROVE_OPTION) {
            text.setText("");
            try {
                in = new BufferedReader(new FileReader(chooser
                        .getSelectedFile().getPath()));
                String line;
                while ((line = in.readLine()) != null) {
                    text.append(line);
                    text.append("\n");
                    text.validate();
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(MainWindow.this, "文件不能打开",
                        "打开文件", JOptionPane.ERROR_MESSAGE);
                e.printStackTrace();
            }
        } else {
            JOptionPane.showMessageDialog(MainWindow.this, "请用户选择需要打开的文件",
                    "打开文件", JOptionPane.WARNING_MESSAGE);
        }
    } // 打开对话框完毕
异常如下
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at mainWindow1.windowOpened(notePad.java:197)
at java.awt.Window.processWindowEvent(Unknown Source)
at javax.swing.JFrame.processWindowEvent(Unknown Source)
at java.awt.Window.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
希望解决下,谢谢

解决方案 »

  1.   

    可能是你定义的String line 没有初始化,将他初始化之后看看,应该不会报异常了
      

  2.   

    可能是你定义的String line 没有初始化,将他初始化之后看看,应该不会报异常了
      

  3.   

    你应该把错误行给我们标出来就好了。如果只分析这一段代码,似乎没有什么错误。
     
    in = new BufferedReader(new FileReader(chooser 
                            .getSelectedFile().getPath())); 
    我只是对这个地方的getSelectedFile().getPath()有点怀疑。你定义一个String,然后把这个String用println()方法打出来看看,你取得的文件路径是否正确,是否完整。
    如果问题真的出在这里。把getPath()改成获取绝对路径的那个方法。因为我在网吧,所以没有测试我的想法,你可以试试。。当遇到问题的时候如果不喜欢使用调试的执行方式,哪么就在你的代码中加System.out.println(),来看你的代码执行情况。这是最笨的方法,却很有效
      

  4.   

         从提示来看 1行 空指针引用  2行 窗体打开错误
          而且swing 不是线程安全的  awt 最好不要和swing 混用