문제

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");
        }
도움이 되었습니까?

해결책

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

다른 팁

Use this to read the file and return a String with your text:

String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append("\n");
        line = br.readLine();
    }
    return sb.toString();
} finally {
    br.close();
}
}

then add the string to your text area by append() method:

table.append(readFile(fileName));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top