与文件相关的NullPointerException



通过这个例子,我试图分解swing元素初始化和操作的逻辑,同时尝试从fileChooser中检索一些信息,用于其他目的。

当我运行它时,在打开一个文件、尝试打开它并将fileCT设置为一个值后,我会得到一个NullPointerException

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class FileOpenTest extends JFrame {
    //====================================================== fields
    JTextField _fileNameTF = new JTextField(15);
    JTextField _wordCountTF = new JTextField(4);
    JFileChooser _fileChooser = new JFileChooser();
    File file = _fileChooser.getSelectedFile();
    //================================================= constructor
    FileOpenTest() {
        //... Create / set component characteristics.
        _fileNameTF.setEditable(false);
        _wordCountTF.setEditable(false);
        //... Add listeners
        //... Create content pane, layout components
        JPanel content = new JPanel();
        content.setLayout(new FlowLayout());
        content.add(new JLabel("File:"));
        content.add(_fileNameTF);
        content.add(new JLabel("Word Count:"));
        content.add(_wordCountTF);
        //... Create menu elements (menubar, menu, menu item)
        JMenuBar menubar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        JMenuItem openItem = new JMenuItem("Open...");
        openItem.addActionListener(new OpenAction());
        //... Assemble the menu
        menubar.add(fileMenu);
        fileMenu.add(openItem);
        //... Set window characteristics
        this.setJMenuBar(menubar);
        this.setContentPane(content);
        this.setTitle("Count Words");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();                      // Layout components.
        this.setLocationRelativeTo(null); // Center window.
    }
    //============================================= countWordsInFile
    private int countWordsInFile(File file) {
        int numberOfWords = 0;  // Count of words.
        try {
            Scanner in = new Scanner(file);
            while (in.hasNext()) {
                String word = in.next();  // Read a "token".
                numberOfWords++;
            }
            in.close();        // Close Scanner's file.
        } catch (FileNotFoundException fnfex) {
            // ... We just got the file from the JFileChooser,
            //     so it's hard to believe there's problem, but...
            JOptionPane.showMessageDialog(FileOpenTest.this,
                    fnfex.getMessage());
        }
        return numberOfWords;
    }
    public int getCountWordsInFile(File file) {
        return this.countWordsInFile(file);
    }
    ///////////////////////////////////////////////////// OpenAction
    class OpenAction implements ActionListener {
        public void actionPerformed(ActionEvent ae) {
            //... Open a file dialog.
            int retval = _fileChooser.showOpenDialog(FileOpenTest.this);
            if (retval == JFileChooser.APPROVE_OPTION) {
                //... The user selected a file, get it, use it.
                //... Update user interface.
                _fileNameTF.setText(file.getName());
                _wordCountTF.setText("" + countWordsInFile(file));
            }
        }
    }
}

以及我初始化窗口的类:

import java.io.File;
import javax.swing.JFrame;
public class FYI {
    static int getCount; 
    static FileOpenTest fOT = new FileOpenTest(); 
    public static void main(String[] args) {
        JFrame window = new FileOpenTest();
        window.setVisible(true);
        File fileCT = fOT.file;
        while (fileCT != null){
                getCount = fOT.getCountWordsInFile(fileCT);
                System.out.print(getCount + "<-- got count!");
        }
    }
}

您读取actionlistener和主方法中的字段file。该字段只写一次,即在初始化类FileOpenTest:时

File file = _fileChooser.getSelectedFile();

这是在JFileChooser被初始化之后直接调用的,并且此时还没有选择任何文件。

调用时,文件选择器将更改其选定的文件。因此,关闭文件对话框后,您需要重新获取文件对象:

//... The user selected a file, get it, use it.
file = _fileChooser.getSelectedFile();  // <= insert something like this here.

相关内容

  • 没有找到相关文章

最新更新