[英]Reading from a file into JTextArea
Im trying to read from a text file into a JTextArea in a GUI. 我试图从文本文件读取到GUI中的JTextArea。 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.
我在文本区域内有一个滚动区域,但是如果尝试读取此文件,则会出现错误,因此我会将其读取到TextArea,但是我不确定这是否正确。
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
. 使用
JTextArea
的read(...)
方法。 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: 然后通过append()方法将字符串添加到您的文本区域:
table.append(readFile(fileName));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.