0

I'm trying to write text-editor type application in Java/Swing. I have the FileChooser working and I can print out the contents of the file to the console. I want to load the file into a JEditorPane

When I call setText(), it updates the value of the text (I can print the result of getText, but the actual EditorPane is not refreshing). I've tried calling repaint/revalidate on the JEditorPane, the encapsulating JScrollPane but nothing will refresh the text to what I sent to setText.

Am I missing something?

P.S. The JEditorPane is wrapped inside a JScrollPane, and I have a method in my mainEditor that passes the string to the setText method of the JEditorPane.

      if (r == JFileChooser.APPROVE_OPTION) 
      {
          FileInputStream fis;
          BufferedReader br;
          try
            {
                fis = new FileInputStream( 
                      chooser.getSelectedFile() ) ;
                br  = new BufferedReader( 
                      new InputStreamReader( fis ) ) ;
                String read ;
                StringBuffer text = new StringBuffer() ;
                while( ( read = br.readLine() ) != null ) 
                {
                   text.append( read ).append( "\n" ) ;
                }
                Main.frame.mainEditor.setText( text.toString() ) ;
                Main.frame.mainEditor.revalidate();
            }
            catch( IOException e1 ) 
            {
                JOptionPane.showMessageDialog( this , 
                    "Error in File Operation" ,
                    "Error in File Operation" , 
                    JOptionPane.INFORMATION_MESSAGE) ;
            }             
      }
Josh
  • 451
  • 8
  • 22
  • If you put the whole code, we might be able to help you. I don't see major issues in your code and simply setting the text should do it. Have you tried replacing your call with a static String like "Some text blah blah blah"? – Guillaume Polet Mar 28 '12 at 11:25

2 Answers2

4

Form the String into a File reference, convert that to an URL then call setPage(URL).

See here for an example.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
3

use built-in methods for InputStream for JTextComponents family

JTextCompoents#read();

JTextComponents#write();

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • 1
    As an aside. This is the better answer. Not only does it refer directly to streams, which the code already mentions, but also covers both input **& output** (which would obviously be required for an editor). +1 (from before) – Andrew Thompson Mar 28 '12 at 12:38
  • 2
    @Andrew Thompson only joke, there are two advantages :-) 1) don't reinvent the wheels, 2) accepting all CR, LR ... separators types from ??? all ??? Native OS where is possible to running Java Apps (only installed JRE) – mKorbel Mar 28 '12 at 12:45