Search code examples
javaswingjtextarea

How to read File and write content into JTextArea?


I want to transfer content from a text file into a JTextarea. I suppose my code just needs small adjustments but even through research. I am not able to find out, what is wrong. So far it is just displaying an empty JFrame instead of the text of the file.

this.setSize(this.width, this.height);
this.setVisible(true);
this.jScrollPane = new JScrollPane(this.jTextArea);
this.jPanel = new JPanel();
this.jPanel.setOpaque(true);
this.jTextArea.setVisible(true);

try {
    this.jTextArea = new JTextArea();
    this.jTextArea.read(new InputStreamReader(
        getClass().getResourceAsStream("C:\\wrk\\SapCommerceCloud\\src\\SwingUni\\name")),
        null);

} // catch

    this.add(this.jScrollPane);

And the usage:

public static void main(String[] args) {
    new TextFrame(new File("C:\\wrk\\SapCommerceCloud\\src\\SwingUni\\name"), 500, 500);
}

Solution

  • You have 2 important issues in this code:

    • You are creating jScrollPane this.jScrollPane = new JScrollPane(this.jTextArea); before reading the file content using jTextArea
    • The method does not work read(new InputStreamReader( getClass().getResourceAsStream("C:\\wrk\\SapCommerceCloud\\src\\SwingUni\\name")), null); Use the one in the following example.

    You have to catch the exception to solve the problems

      public class TextAreaDemo extends JFrame {
    
        private JScrollPane jScrollPane;
        private JTextArea jTextArea ;
        private static final String FILE_PATH="/Users/user/IdeaProjects/StackOverflowIssues/file.txt";
    
     public TextAreaDemo() {
    
            try {
                jTextArea = new JTextArea(24, 31);
    
                jTextArea.read(new BufferedReader(new FileReader(FILE_PATH)), null);
    
            } catch (Exception e){
    
                e.printStackTrace();
            }
    
            jScrollPane = new JScrollPane(this.jTextArea);
            this.add(this.jScrollPane);
            this.setVisible(true);
            this.setSize(400, 200);
        }
        public static void main(String[] args) {
            TextAreaDemo textAreaDemo = new TextAreaDemo();
        }