2011-03-01 77 views
0

好吧......我剛開始使用Java,並且已經加強到了Swing GUI。一切都很順利,直到我嘗試使用文件輸入和輸出。Java Swing文本編輯器拋出NullPointerException

/* 
    ** 'Gooey' GUI in Swing with Java. 
    ** v3 With File Opening 
    */ 

    import javax.swing.*; // Import the swing library 
    import javax.swing.filechooser.*; 
    import java.awt.*; // Import library 
    import java.awt.event.*; // Import event handling 
    import java.io.*; 
    import java.nio.*; 
    import java.nio.charset.*; 

    class gooey implements ActionListener { 

     JFrame myFrame = null; // Create a JFrame, don't fill it 
     JEditorPane myPane = null; 
     String fileName = "myJava.java"; 
     Font editorFont = new Font("Consolas",Font.PLAIN, 12); 

     public static void main(String[] args) { 
      (new gooey()).test(); // Create a GUI and 'test' it 
     } 

     private void test() { // Test run of a gooey 

      // FRAME 
      ////////// 
      System.out.println("Creating myFrame..."); // Debug stuff 

      myFrame = new JFrame("Gooey"); // Create a new JFrame (window) 
      myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // Set it so that when the [X] button is clicked, the app exits 
      myFrame.setSize(400,300); // Set the size of 400x300px (WxH) 

      System.out.println("myFrame created!"); // Debug stuff 

      // MENU BAR 
      ///////////// 
      System.out.println("Creating menuBar..."); // Debug stuff 

      JMenuBar myBar = new JMenuBar(); // Create a new JMenuBar called myBar 

      System.out.println("Done!"); // More debug stuff 
      System.out.println("Creating JButtons..."); 

      JButton openButton = new JButton("Open"); // Create a button named openButton 
      openButton.addActionListener(this); 

      JButton saveButton = new JButton("Save"); // Create a button named saveButton 
      saveButton.addActionListener(this); 

      JButton quitButton = new JButton("Quit"); // Create a button named quitButton 
      quitButton.addActionListener(this); // Add an actionListener 

      myBar.add(openButton); // Add the buttons to the menubar 
      myBar.add(saveButton); 
      myBar.add(quitButton); 

      System.out.println("Done!"); // Even more debug stuff 

      // EDITOR PANE 
      //////////////// 
      System.out.println("Creating myPane..."); // EVEN MOAR DEBUG 

      JEditorPane myPane = new JEditorPane(); // Create a new JEditorPane called myPane 
      myPane.setContentType("text/plain"); // Set it so that it can only edit plain text 
      myPane.setFont(editorFont); 
      myPane.setText(
       "This is a JEditorPane." 
       +"\nIt can display text/rich text/HTML that can be edited."); // Set the starting text of myPane to that 

      System.out.println("Done!"); // And yet more debug stuff 

      // RUNNING IT 
      /////////////// 
      System.out.println("Running it all..."); // DEBUG 

      myFrame.setJMenuBar(myBar); // Set the frame's menu bar to myBar 
      myFrame.setContentPane(myPane); // Set it so that the content in myFrame is myPane 
      myFrame.setVisible(true); // Make myFrame visible 

      System.out.println("myFrame has been created!"); 
     } 

     // ACTION LISTENERS 
     ///////////////////// 

     public void actionPerformed(ActionEvent e) { 

     // Basically, every time an action is performed (e.g. left mouse click) 
     // on something with an actionListener attached to it, we can call this 
     // method. 

      if (e.getActionCommand()=="Quit") System.exit(0); // If the string of the thing we're listening to was "quit", exit the program! 
      else { 

       // CREATE A FILE CHOOSER 
       ///////////////////////// 
       JFileChooser myFileChoose = new JFileChooser(); 
       myFileChoose.setCurrentDirectory(new File("C:")); 
       myFileChoose.setSelectedFile(new File(fileName)); 
       myFileChoose.setFileSelectionMode(JFileChooser.FILES_ONLY); 

       FileNameExtensionFilter myFilter = new FileNameExtensionFilter(".java files","java"); 
       myFileChoose.setFileFilter(myFilter); 

       try { 
        // OPEN COMMAND 
        ///////////////// 
        if (e.getActionCommand()=="Open") { 
         int r = myFileChoose.showOpenDialog(myPane);      // Create a file chooser 
         if (r == JFileChooser.APPROVE_OPTION) {       // If the user has selected a file 
          File selectedFile = myFileChoose.getSelectedFile();    // Find that file 
          fileName = selectedFile.getName();      // Get it's name and store it in a variable 
          FileInputStream fis = new FileInputStream(selectedFile);   // Stream the input 
          InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8")); // Read said stream 
          char[] buffer = new char[1024];       // Create a buffer 
          int n = isr.read(buffer);       // Read from the input and buffer 
          String text = new String(buffer, 0, n);      // Put into string 
          myPane.setText(text);        // Put into JEditorPane 
          isr.close(); 
         } 
        // SAVE COMMAND 
        ///////////////// 
        } else if (e.getActionCommand()=="Save") { 
         int r = myFileChoose.showOpenDialog(myPane); 
         if (r == JFileChooser.APPROVE_OPTION) {        // If the user has selected a file 
          File selectedFile = myFileChoose.getSelectedFile();     // Find that file 
          fileName = selectedFile.getName();       // Get it's name and store it in a variable 
          FileOutputStream fos = new FileOutputStream(selectedFile);    // Stream the input 
          OutputStreamWriter osr = new OutputStreamWriter(fos, Charset.forName("UTF-8"));  // Read said stream 
          osr.write(myPane.getText()); 
          osr.close(); 
         } 
        } 
       } catch (Exception q) { 
        q.printStackTrace(); 
       } 
      } 
     } 

    } 

我儘量做到工作,但是當我嘗試打開或保存通過一個JFileChooser一個文件,它讓我看到這些:

打開文件錯誤:

 
java.lang.NullPointerException at gooey.actionPerformed(gooey.java:120) 

保存文件錯誤:

 
java.lang.NullPointerException at gooey.actionPerformed(gooey.java:132) 
+0

馬克線120和132在您的源代碼,請。 – 2011-03-01 08:39:46

+0

你需要檢查文件是否存在,文件是否存在,這將檢查文件是否存在,如果不存在,你會得到一個空指針,如果你打算使用文件IO,那麼更好檢查以確保它退出。 if(file.exists()){} – Jim 2011-03-01 08:41:08

+1

另外,使用.equals()來檢查'String's的相等性,而不是'=='。 – asgs 2011-03-01 08:42:33

回答

2

可變myPane未初始化(null )。這導致NullPointerException

您創建一個新的JEditorPane(約65行),但其分配到一個局部變量,因此具有相同名稱的類成員仍然是null(和actionPerformed使用類成員變量myPane)。更改行65

JEditorPane myPane = new JEditorPane(); 

myPane = new JEditorPane(); 
相關問題