I was trying to read a file and print it to the JTextArea in other class. My program complies but its not printing the file content in JTextArea.

Here is my MouselIstener Code

class MySaveMouseListener extends MouseAdapter {
            MyClass1 myobj = new MyClass1();
            public javax.swing.JTextField myjtext = myobj.getTextField();
            public String file_string;
         
            public String readFile (File file) {
                 StringBuffer fileBuffer;
                 String fileString=null;
                 String line;
               try {
                    FileReader in = new FileReader (file);
                    BufferedReader dis = new BufferedReader (in);
                    fileBuffer = new StringBuffer () ;
 
               while ((line = dis.readLine ()) != null) { 
                     fileBuffer.append (line + "\n");
               }
                     in.close ();
                     fileString = fileBuffer.toString ();
               }
               catch (IOException e ) {
                    return null;
               }
                    return fileString ;
            }
  public void mouseClicked(MouseEvent evt) {
              JFileChooser chooser = new JFileChooser();
              chooser.setCurrentDirectory(new File("."));
              chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
              chooser.showSaveDialog(myjtext);
              File selectedPfile = chooser.getSelectedFile();
              myjtext.setText(selectedPfile.getAbsolutePath());
              MySaveMouseListener wah = new MySaveMouseListener();
              file_string = wah.readFile(selectedPfile);
              
              
 
  }/*
  public static void main(String args[]) {
      MySaveMouseListener wgh = new MySaveMouseListener();
      wgh.readFile(null);
  }*/
}

Then I call it in Class1 method like this:-

fTextArea = new JTextArea ("");
        MySaveMouseListener won = new MySaveMouseListener();
        if (won.file_string != null)
        fTextArea.setText (won.file_string);

Why is it not printing the text file contents in the JTextArea even though I am trying to do that ?

Thanks in advance

Don't know why it fails, but you catch IOException and just return null - so if there is an IO problem you will get no error messages or any other clues as to what happened. Put a e.printStackTrace(); in the catch and see if there's a problem there.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.