Search code examples
javaswingfile-iojtextarea

Reading from a file into JTextArea


Im trying to read from a text file into a JTextArea in a GUI. But the text is not appearing. I have a scroll area within my text area but I get an error if I try to read the file to this so im reading it to the TextArea, but im not sure if this is correct.

String readFrom = "C:\\Users\\john\\directory.txt";
    int num;
    String line;

    Scanner inFile = new Scanner(new FileReader(readFrom));
    BufferedReader in = new BufferedReader(new FileReader(readFrom));
    num = inFile.nextInt();



JTextArea table = new JTextArea(55, 15);       //text area for directory
    JScrollPane table1  = new JScrollPane(table);
    table.setEditable(false);
    panel.add(table1);

    for( int i=0; i< num; i++){
        line = in.readLine();
        table.read(in, "table1");
        }

Solution

  • Use the read(...) method of the JTextArea. It will do the reading of the text from the file for you.