0

我正在尝试在我在 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");
    }
4

3 回答 3

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);
于 2011-04-10T17:43:32.300 回答
0

我认为您正在覆盖 line 变量。

line+=...

连接,然后设置循环外连接的整行的值。

于 2011-04-10T17:45:15.073 回答
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);
于 2011-04-10T17:46:39.677 回答