我正在尝试显示我在GUI中创建的JTextArea中的文本文件中的信息。我已经想出如何从文件中获取信息到JTextArea,但它只抓取文件的最后一行。我需要显示所有的行。我不断改变循环,但无法弄清楚这个。任何帮助将不胜感激。以下是我的代码:
public TextArea() {
initComponents();
try {
FileReader one = new FileReader ("info.txt");
BufferedReader buf = new BufferedReader(one);
String line = "";
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
//textArea.setText(line);
while ((line = buf.readLine()) != null) {
lineNumber++;
//break comma separated line using ","
st = new StringTokenizer(line, ",");
while (st.hasMoreTokens()) {
//display csv values
tokenNumber++;
line = ("Title: " + st.nextToken()
+ "\n" + "Make:" + st.nextToken()
+ "\n" + "Model:" + st.nextToken()
+ "\n" + "Year:" + st.nextToken()
+ "\n" + "Price:" + st.nextToken()
+ "\n" + "Notes:" + st.nextToken()
+ "\n" + "Details:" + st.nextToken()
+ "\n");
textArea.setText(line);
}
//reset token number
tokenNumber = 0;
//textArea.setText(line);
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(this, "File not found");
} catch (IOException e){
JOptionPane.showMessageDialog(this, "Data not read");
}
答案 0 :(得分:1)
看看你的代码:
while (st.hasMoreTokens()) {
//display csv values
tokenNumber++;
line = ("Title: " + st.nextToken()
+ "\n" + "Make:" + st.nextToken()
+ "\n" + "Model:" + st.nextToken()
+ "\n" + "Year:" + st.nextToken()
+ "\n" + "Price:" + st.nextToken()
+ "\n" + "Notes:" + st.nextToken()
+ "\n" + "Details:" + st.nextToken()
+ "\n");
textArea.setText(line);
}
每次找到新令牌时,都会将textarea val设置为找到的最后一个令牌。 所以显然文本区域只显示最后一行。 您可以尝试以下方式:
textArea.setText(textArea.getText() + line);
答案 1 :(得分:0)
我认为你正在重写线变量。
line+=...
连接,然后设置在循环外连接的整行的值。
答案 2 :(得分:0)
while (st.hasMoreTokens()) {
//display csv values
tokenNumber++;
line = line +"\n"+("Title: " + st.nextToken()
+ "\n" + "Make:" + st.nextToken()
+ "\n" + "Model:" + st.nextToken()
+ "\n" + "Year:" + st.nextToken()
+ "\n" + "Price:" + st.nextToken()
+ "\n" + "Notes:" + st.nextToken()
+ "\n" + "Details:" + st.nextToken()
+ "\n");
}
textArea.setText(line);