Results 1 to 8 of 8
  1. #1
    Rtme is offline Member
    Join Date
    May 2011
    Posts
    11
    Rep Power
    0

    Exclamation JFileChooser Odd Error?

    "Solved ish - if anyone knows how to stop the JFileChooser from closing after 5 seconds please help..."

    Hi, I tried to do an example from a book, however for some odd reason the JFileChooser closes with an error... I searched on google but could not find any help...

    Code:
    Java Code:
    import java.io.*; 
    import java.awt.*; 
    import java.awt.event.*; 
    import javax.swing.*; 
    import javax.swing.event.*; 
      
    class Main { 
     
      JLabel jlabMsg; 
      
      JTextArea jta; 
     
     JFileChooser jfc;
      
      JTextField jtfFName; 
      JTextField jtfFind; 
     
      JButton jbtnSave; 
      JButton jbtnLoad; 
      JButton jbtnFind; 
      JButton jbtnFindNext; 
     
      int findIdx; 
     
      public Main() { 
     
        // Create a new JFrame container. 
        JFrame jfrm = new JFrame("A Simple Text Editor"); 
     
        // Specify FlowLayout for the layout manager. 
        jfrm.getContentPane().setLayout(new FlowLayout()); 
     
        // Give the frame an initial size. 
        jfrm.setSize(270, 420); 
     
        // Terminate the program when the user closes the application. 
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        
        
        jfc = new JFileChooser();
        
        
        
        JMenuBar  menu = new JMenuBar();
        
        JMenu menuFile = new JMenu("File");
        JMenu menuEdit = new JMenu("Edit");
        JMenu menuHelp = new JMenu("Help");
      
        JMenuItem menuItemSave = new JMenuItem("Save");
        JMenuItem menuItemAbout = new JMenuItem("About");
        JMenuItem menuItemSelectall = new JMenuItem("Select All");
        JMenuItem menuItemOpen = new JMenuItem("Open");
        JMenuItem menuItemFind = new JMenuItem("Find");
        
        menuHelp.add(menuItemAbout);
        menuEdit.add(menuItemSelectall);
        menuFile.add(menuItemSave);
        menuFile.add(menuItemOpen);
        menuEdit.add(menuItemFind);
        
        menu.add(menuFile);
        menu.add(menuEdit);
        menu.add(menuHelp);
        
        menuItemSave.addActionListener(new ActionListener() {    
            public void actionPerformed(ActionEvent le) {  
              save(); 
            }    
          }); 
    
        menuItemOpen.addActionListener(new ActionListener() {    
            public void actionPerformed(ActionEvent le) {  
              load(); 
            }    
          }); 
        
        jfrm.add(menu);
        //menuFile.setToolTipText("YAY");
        
        // Create the message label. 
        jlabMsg = new JLabel(); 
        jlabMsg.setPreferredSize(new Dimension(200, 30)); 
        jlabMsg.setHorizontalAlignment(SwingConstants.CENTER); 
     
        // Create an empty label to add space. 
        JLabel jlabSeparator = new JLabel(); 
        jlabSeparator.setPreferredSize(new Dimension(200, 30)); 
     
        // Create the Seach For and Filename labels. 
        JLabel jlabFind = new JLabel("Search For:"); 
        jlabFind.setPreferredSize(new Dimension(70, 20)); 
        jlabFind.setHorizontalAlignment(SwingConstants.RIGHT); 
     
        JLabel jlabFilename = new JLabel("Filename:"); 
        jlabFilename.setPreferredSize(new Dimension(70, 20)); 
        jlabFilename.setHorizontalAlignment(SwingConstants.RIGHT); 
     
        // Create the text field. 
        jta = new JTextArea(); 
         jta.setBackground(Color.YELLOW);
         
         // Put the text area into a scroll pane. 
        JScrollPane jscrlp = new JScrollPane(jta); 
        jscrlp.setPreferredSize(new Dimension(250, 200)); 
     
        // Create text field for filename. 
        jtfFName = new JTextField(15); 
     
        // Add a caret listener for the text area. This 
        // handler displays number of characters in the  
        // file. It is updated with each caret change. 
        // The findIdx variable is also set to the current 
        // caret loction. 
        jta.addCaretListener(new CaretListener() {    
          public void caretUpdate(CaretEvent ce) { 
            String str = jta.getText(); 
            jlabMsg.setText("Current size: " + str.length()); 
            findIdx = jta.getCaretPosition(); 
          }    
        }); 
     
        // Create the Save and Load buttons. 
        jbtnSave = new JButton("Save File"); 
        jbtnLoad = new JButton("Load File"); 
     
        // Add action listener for the Save button. 
        jbtnSave.addActionListener(new ActionListener() {    
          public void actionPerformed(ActionEvent le) {  
            save(); 
          }    
        });  
     
        // Add action listener for the Load button. 
        jbtnLoad.addActionListener(new ActionListener() {    
          public void actionPerformed(ActionEvent le) {  
            load(); 
          }    
        });  
     
        // Create the Search For text field. 
        jtfFind = new JTextField(15); 
     
        // Create the Find From Top and Find Next buttons. 
        jbtnFind = new JButton("Find From Top"); 
        jbtnFindNext = new JButton("Find Next"); 
     
        // Add action listener for the Find button. 
        jbtnFind.addActionListener(new ActionListener() {    
          public void actionPerformed(ActionEvent le) {  
            findIdx = 0; 
            find(findIdx); 
          }    
        });  
     
        // Add action listener for the Find Next button. 
        jbtnFindNext.addActionListener(new ActionListener() {    
          public void actionPerformed(ActionEvent le) {  
            find(findIdx+1); 
          }    
        });  
     
        // Add the components to the content pane. 
        Container cp = jfrm.getContentPane(); 
        cp.add(jscrlp);  
        cp.add(jlabFind); 
        cp.add(jtfFind); 
        cp.add(jbtnFind); 
        cp.add(jbtnFindNext); 
        cp.add(jlabSeparator); 
        cp.add(jlabFilename);  
        cp.add(jtfFName); 
       // cp.add(jbtnSave); 
      //  cp.add(jbtnLoad);    
        cp.add(jlabMsg); 
     
        // Display the frame. 
        jfrm.setVisible(true); 
      } 
     
      // Save the file. 
      void save() { 
        FileWriter fw; 
     
        // Get the filename from the text field. 
        String fname = jtfFName.getText(); 
             
        // Make sure that there is actually a filename present. 
        if(fname.length() == 0) { 
          jlabMsg.setText("No filename present."); 
          return; 
        } 
     
        // Save the file. 
        try { 
          fw = new FileWriter(fname); 
          jta.write(fw); 
          fw.close(); 
        } catch(IOException exc) { 
          jlabMsg.setText("Error opening or writing file."); 
          return; 
        } 
     
        jlabMsg.setText("File written sucessfully."); 
      } 
     
      // Load the file. 
      void load() { 
    	  
    	  int result = jfc.showOpenDialog(null);
    	  
    	  
    	 // try {
    	//	Thread.sleep(2222222);
    	//} catch (InterruptedException e) {
    		// TODO Auto-generated catch block
    	//	e.printStackTrace();
    	//}
    	  FileReader fw; 
     
        // Get the filename from the text field. 
        //String fname = jtfFName.getText(); 
    	  String fname = jfc.getSelectedFile().getName(); 
       fname = "notes.txt";
    	  // Make sure that there is actually a filename present. 
        if(fname.length() == 0) { 
          jlabMsg.setText("No filename present."); 
          return; 
        } 
     
        // Load the file. 
        try { 
        	//showOpenDialog();
          fw = new FileReader(fname); 
          jta.read(fw, null); 
          fw.close(); 
        } catch(IOException exc) { 
          jlabMsg.setText("Error opening or reading file."); 
          return; 
        } 
     
        // Reset find index when a new file is loaded. 
        findIdx = 0; 
     
        jlabMsg.setText("File loaded successfully."); 
      } 
     
      // Search the file. 
      void find(int start) { 
        // Get the current text as a string. 
        String str = jta.getText(); 
     
        str = str.toLowerCase();
        
        // Get the string to find. 
        String findStr = jtfFind.getText(); 
        
        findStr = findStr.toLowerCase();
       
        // Beginning at start, find the first 
        // occureance of the specified string. 
        int idx = str.indexOf(findStr, start); 
     
        // See if there is a match. 
        if(idx > -1) {           
          // If found, set focus to text area 
          // and move caret to the location. 
          jta.setCaretPosition(idx); 
          findIdx = idx; // update the find index 
          jlabMsg.setText("String found."); 
        } 
        else 
          jlabMsg.setText("String not found."); 
     
        // Set the focus to the editor window. 
        jta.requestFocusInWindow(); 
      } 
     
      public static void main(String args[]) { 
        // Create the frame on the event dispatching thread. 
        SwingUtilities.invokeLater(new Runnable() { 
          public void run() { 
            new Main(); 
          } 
        }); 
      } 
    }
    And the error:
    Java Code:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
       at Main.load(Main.java:221)
       at Main$2.actionPerformed(Main.java:72)
       at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2015)
       at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2338)
       at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
       at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
       at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
       at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:833)
       at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:877)
       at java.awt.Component.processMouseEvent(Component.java:6434)
       at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
       at java.awt.Component.processEvent(Component.java:6199)
       at java.awt.Container.processEvent(Container.java:2203)
       at java.awt.Component.dispatchEventImpl(Component.java:4790)
       at java.awt.Container.dispatchEventImpl(Container.java:2261)
       at java.awt.Component.dispatchEvent(Component.java:4616)
       at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4803)
       at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4463)
       at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4393)
       at java.awt.Container.dispatchEventImpl(Container.java:2247)
       at java.awt.Window.dispatchEventImpl(Window.java:2671)
       at java.awt.Component.dispatchEvent(Component.java:4616)
       at java.awt.EventQueue.dispatchEvent(EventQueue.java:662)
       at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
       at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
       at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
       at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
       at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
       at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
    If anyone can help... :confused:
    Last edited by Rtme; 05-16-2011 at 05:13 PM. Reason: Solved ish

  2. #2
    pawdlk is offline Member
    Join Date
    May 2011
    Posts
    7
    Rep Power
    0

    Default

    Hi, in load method you have "result" variable of type int that is not used. This variable holds values returned by showOpenDialog. While "Open" Dialog is closed then you try to fname = jfc.getSelectedFile().getName(); no matter if any file was selected or not. It looks like you click "Cancel" on Open Dialog Box, no file is selected so jfc.getSelectedFile() is null and you try to invoke getName(); on NULL object. Quick solution to this would be

    Java Code:
    String fname = "";
    if (result == 0 ){
    	fname = jfc.getSelectedFile().getName(); 
    }

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by pawdlk View Post
    Hi, in load method you have "result" variable of type int that is not used. ...
    Nice spot and welcome to the Java-Forums!

  4. #4
    Rtme is offline Member
    Join Date
    May 2011
    Posts
    11
    Rep Power
    0

    Default

    Thanks... But It diddn't work for me (Or I have put it in wrong) I am still getting the error and I forgot to mention on the OP, the file chooser exits after about 5 seconds... And I got the same thing on the netbeans filechooser, so i am not sure if my java install is corrupted...

    But yeah, Here is my revised code:

    Java Code:
    import java.io.*; 
    import java.awt.*; 
    import java.awt.event.*; 
    import javax.swing.*; 
    import javax.swing.event.*; 
      
    class Main { 
     
      JLabel jlabMsg; 
      
      JTextArea jta; 
     
     JFileChooser jfc;
     JFileChooser jfc2; 
     
      JTextField jtfFName; 
      JTextField jtfFind; 
     
      JButton jbtnSave; 
      JButton jbtnLoad; 
      JButton jbtnFind; 
      JButton jbtnFindNext; 
      JFrame jfrm;
      int findIdx; 
     
      public Main() { 
     
        // Create a new JFrame container. 
        jfrm = new JFrame("A Simple Text Editor"); 
     
        // Specify FlowLayout for the layout manager. 
        jfrm.getContentPane().setLayout(new FlowLayout()); 
     
        // Give the frame an initial size. 
        jfrm.setSize(270, 420); 
     
        // Terminate the program when the user closes the application. 
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        
        
        jfc = new JFileChooser();
        
        
        
        JMenuBar  menu = new JMenuBar();
        
        JMenu menuFile = new JMenu("File");
        JMenu menuEdit = new JMenu("Edit");
        JMenu menuHelp = new JMenu("Help");
      
        JMenuItem menuItemSave = new JMenuItem("Save");
        JMenuItem menuItemAbout = new JMenuItem("About");
        JMenuItem menuItemSelectall = new JMenuItem("Select All");
        JMenuItem menuItemOpen = new JMenuItem("Open");
        JMenuItem menuItemFind = new JMenuItem("Find");
        
        menuHelp.add(menuItemAbout);
        menuEdit.add(menuItemSelectall);
        menuFile.add(menuItemSave);
        menuFile.add(menuItemOpen);
        menuEdit.add(menuItemFind);
        
        menu.add(menuFile);
        menu.add(menuEdit);
        menu.add(menuHelp);
        
        menuItemSave.addActionListener(new ActionListener() {    
            public void actionPerformed(ActionEvent le) {  
              save(); 
            }    
          }); 
    
        menuItemOpen.addActionListener(new ActionListener() {    
            public void actionPerformed(ActionEvent le) {  
              load(); 
            }    
          }); 
        
        jfrm.add(menu);
        //menuFile.setToolTipText("YAY");
        
        // Create the message label. 
        jlabMsg = new JLabel(); 
        jlabMsg.setPreferredSize(new Dimension(200, 30)); 
        jlabMsg.setHorizontalAlignment(SwingConstants.CENTER); 
     
        // Create an empty label to add space. 
        JLabel jlabSeparator = new JLabel(); 
        jlabSeparator.setPreferredSize(new Dimension(200, 30)); 
     
        // Create the Seach For and Filename labels. 
        JLabel jlabFind = new JLabel("Search For:"); 
        jlabFind.setPreferredSize(new Dimension(70, 20)); 
        jlabFind.setHorizontalAlignment(SwingConstants.RIGHT); 
     
        JLabel jlabFilename = new JLabel("Filename:"); 
        jlabFilename.setPreferredSize(new Dimension(70, 20)); 
        jlabFilename.setHorizontalAlignment(SwingConstants.RIGHT); 
     
        // Create the text field. 
        jta = new JTextArea(); 
         jta.setBackground(Color.YELLOW);
         
         // Put the text area into a scroll pane. 
        JScrollPane jscrlp = new JScrollPane(jta); 
        jscrlp.setPreferredSize(new Dimension(250, 200)); 
     
        // Create text field for filename. 
        jtfFName = new JTextField(15); 
     
        // Add a caret listener for the text area. This 
        // handler displays number of characters in the  
        // file. It is updated with each caret change. 
        // The findIdx variable is also set to the current 
        // caret loction. 
        jta.addCaretListener(new CaretListener() {    
          public void caretUpdate(CaretEvent ce) { 
            String str = jta.getText(); 
            jlabMsg.setText("Current size: " + str.length()); 
            findIdx = jta.getCaretPosition(); 
          }    
        }); 
     
        // Create the Save and Load buttons. 
        jbtnSave = new JButton("Save File"); 
        jbtnLoad = new JButton("Load File"); 
     
        // Add action listener for the Save button. 
        jbtnSave.addActionListener(new ActionListener() {    
          public void actionPerformed(ActionEvent le) {  
            save(); 
          }    
        });  
     
        // Add action listener for the Load button. 
        jbtnLoad.addActionListener(new ActionListener() {    
          public void actionPerformed(ActionEvent le) {  
            load(); 
          }    
        });  
     
        // Create the Search For text field. 
        jtfFind = new JTextField(15); 
     
        // Create the Find From Top and Find Next buttons. 
        jbtnFind = new JButton("Find From Top"); 
        jbtnFindNext = new JButton("Find Next"); 
     
        // Add action listener for the Find button. 
        jbtnFind.addActionListener(new ActionListener() {    
          public void actionPerformed(ActionEvent le) {  
            findIdx = 0; 
            find(findIdx); 
          }    
        });  
     
        // Add action listener for the Find Next button. 
        jbtnFindNext.addActionListener(new ActionListener() {    
          public void actionPerformed(ActionEvent le) {  
            find(findIdx+1); 
          }    
        });  
     
        // Add the components to the content pane. 
        Container cp = jfrm.getContentPane(); 
        cp.add(jscrlp);  
        cp.add(jlabFind); 
        cp.add(jtfFind); 
        cp.add(jbtnFind); 
        cp.add(jbtnFindNext); 
        cp.add(jlabSeparator); 
        cp.add(jlabFilename);  
        cp.add(jtfFName); 
       // cp.add(jbtnSave); 
      //  cp.add(jbtnLoad);    
        cp.add(jlabMsg); 
     
        // Display the frame. 
        jfrm.setVisible(true); 
      } 
     
      // Save the file. 
      void save() { 
        FileWriter fw; 
     
        // Get the filename from the text field. 
       
        File fname = jfc2.getSelectedFile(); 
        
        while (jfc2.getSelectedFile()== null)
        {
        	jfc.showSaveDialog(jfrm);
        }
        
        // Make sure that there is actually a filename present. 
        if(fname.length() == 0) { 
          jlabMsg.setText("No filename present."); 
          return; 
        } 
     
        // Save the file. 
        try { 
          fw = new FileWriter(fname); 
          jta.write(fw); 
          fw.close(); 
        } catch(IOException exc) { 
          jlabMsg.setText("Error opening or writing file."); 
          return; 
        } 
     
        jlabMsg.setText("File written sucessfully."); 
      } 
     
      // Load the file. 
      void load() { 
    	  int result = 0;
    	
    		  jfc.showOpenDialog(jfrm);
    	
    	String fname = "";
    	 
    	  if (result == 0 ){
    	  File file = jfc.getSelectedFile();
    	 fname = file.getPath();
    	  }
    	    
    	
    	
    	
    	
    	  
    	if (result == JFileChooser.APPROVE_OPTION)
    	{
    		System.out.println("Debug: Something happned");
    	}
    	
    	
    	  FileReader fw; 
     
        // Get the filename from the text field. 
      
    	  // Make sure that there is actually a filename present. 
        if(fname.length() == 0) { 
          jlabMsg.setText("No filename present."); 
          return; 
        } 
     
        // Load the file. 
        try { 
        	//showOpenDialog();
          fw = new FileReader(fname); 
          jta.read(fw, null); 
          fw.close(); 
        } catch(IOException exc) { 
          jlabMsg.setText("Error opening or reading file."); 
          return; 
        } 
     
        // Reset find index when a new file is loaded. 
        findIdx = 0; 
     
        jlabMsg.setText("File loaded successfully."); 
     //omnom = null;
      } 
     
      // Search the file. 
      void find(int start) { 
        // Get the current text as a string. 
        String str = jta.getText(); 
     
        str = str.toLowerCase();
        
        // Get the string to find. 
        String findStr = jtfFind.getText(); 
        
        findStr = findStr.toLowerCase();
       
        // Beginning at start, find the first 
        // occureance of the specified string. 
        int idx = str.indexOf(findStr, start); 
     
        // See if there is a match. 
        if(idx > -1) {           
          // If found, set focus to text area 
          // and move caret to the location. 
          jta.setCaretPosition(idx); 
          findIdx = idx; // update the find index 
          jlabMsg.setText("String found."); 
        } 
        else 
          jlabMsg.setText("String not found."); 
     
        // Set the focus to the editor window. 
        jta.requestFocusInWindow(); 
      } 
     
      public static void main(String args[]) { 
        // Create the frame on the event dispatching thread. 
        SwingUtilities.invokeLater(new Runnable() { 
          public void run() { 
            new Main(); 
          } 
        }); 
      } 
    }

  5. #5
    pawdlk is offline Member
    Join Date
    May 2011
    Posts
    7
    Rep Power
    0

    Default

    What you did here does not make sense:

    Java Code:
    int result = 0;
    	
    		  jfc.showOpenDialog(jfrm);
    	
    	String fname = "";
    	 
    	  if (result == 0 ){
    	  File file = jfc.getSelectedFile();
    	 fname = file.getPath();
    	  }
    result is always 0 because it is not modified in any way between its declaration and initialization and if clause. So if (result == 0 ) statement is always true.

    fname = file.getPath(); statement throws an exception when file object does not exist

  6. #6
    Rtme is offline Member
    Join Date
    May 2011
    Posts
    11
    Rep Power
    0

    Default

    Ah thanks, I changed the some of the code and then forgot and tried to use the solution that applied to the old code!

    Now the error message is gone, but it still closes after a few seconds. I have reinstalled java but it made no difference... I suspect that it is my computer... But if anyone has any ideas...?

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Rtme View Post
    Ah thanks, I changed the some of the code and then forgot and tried to use the solution that applied to the old code!

    Now the error message is gone, but it still closes after a few seconds. I have reinstalled java but it made no difference... I suspect that it is my computer... But if anyone has any ideas...?
    Quit suspecting -- you have a bug in your code, pure and simple. I'd try paring down the code, perhaps by commenting out, until the error goes away and then check what what just commented out.

  8. #8
    Rtme is offline Member
    Join Date
    May 2011
    Posts
    11
    Rep Power
    0

Similar Threads

  1. jFileChooser
    By ArneBassez in forum AWT / Swing
    Replies: 7
    Last Post: 12-01-2010, 04:38 AM
  2. jfilechooser
    By ranadav in forum AWT / Swing
    Replies: 7
    Last Post: 06-03-2010, 02:44 PM
  3. Jfilechooser
    By greatmajestics in forum Java 2D
    Replies: 5
    Last Post: 03-30-2010, 06:13 PM
  4. Need JFileChooser Help
    By Wraithier in forum New To Java
    Replies: 4
    Last Post: 06-18-2008, 05:40 PM
  5. how to use JFileChooser
    By tommy in forum New To Java
    Replies: 1
    Last Post: 08-06-2007, 08:49 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •