开发者

NullPointerException related to File

Working from this example, I'm trying to break up the logic from the swing elements initialization and actions, while trying retrieve some information from the fileChooser, for other purposes.

When I run it, I get a NullPointerException after I open a file, attempt to open it, and setting fileCT to a value.

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,
            开发者_如何学Go        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));
            }
        }
    }
}

and the class I'm initializing the window from:

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


You read the field file within your actionlistener and your main method. This field is only written once, namely in the initialization of class FileOpenTest:

File file = _fileChooser.getSelectedFile();

This is called straight after the JFileChooser is instanciated and at this point no file is selected yet.

The file chooser will change its selected file when called. Thus, after the file dialog is closed you need to re-get the file object:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜