2011-06-28 43 views
0

this example開始,我嘗試從swing元素的初始化和動作中分離邏輯,同時嘗試從fileChooser中檢索某些信息,用於其他目的。與文件相關的NullPointerException

當我運行它時,我打開一個文件,嘗試打開它,並將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!"); 
     } 
    } 
} 
+1

它幫助很多,如果你告訴我們_where_(其中的代碼行)的空指針異常發生。 – Howard

+0

在_fileNameTF.setText(file.getName())時發生空指針異常; – DOLOisSOLO

回答

2

你讀你的ActionListener和你的主要方法中的場file。該JFileChooser被實例化後

File file = _fileChooser.getSelectedFile(); 

這被稱爲直在這一點上沒有文件尚未選擇:該字段只能寫一次,即在FileOpenTest類的初始化。

文件選擇器在被調用時將更改其選定的文件。因此,文件對話框關閉後,你需要重新獲得文件對象:

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

這確實照顧了空指針異常,但我仍然無法從:while(fileCT!= null)得到任何輸出:{getCount = fOT.getCountWordsInFile(fileCT); System.out.print(getCount +「< - got count!」); }在我的主要方法。 – DOLOisSOLO

+0

@DOLOisSOLO問題在於'window.setVisible(true)'不會等到窗口關閉或發生任何操作。相反,主要的方法會一直運行,並且此時您還沒有選擇任何文件。因此'fOT.file'爲空。因此將這些代碼放在'main()'中是沒有意義的。請閱讀[swing編程入門](http://download.oracle.com/javase/tutorial/uiswing/TOC.html)。 – Howard

相關問題