尝试从txt文件向jList添加项目

时间:2011-07-19 18:59:05

标签: java swing netbeans jframe jlist

我有以下尝试在单击按钮时执行的catch块。

  try {
//picking up the file I want to read in
 BufferedReader in = new BufferedReader(new FileReader("C:\\users\\me\\desktop\\blah.txt"));
 String line;                                           
 try {
    //read through the file until there is nothing left and add each line to list
         while((line = in.readLine()) != null){  
            jList1.add(line, jList1);
                    }

               } catch (IOException ex) {
                    Logger.getLogger(Frame2.class.getName()).log(Level.SEVERE, null, ex);
           }
      } catch (FileNotFoundException ex) {
                Logger.getLogger(Frame2.class.getName()).log(Level.SEVERE, null, ex);
  }

我可以成功System.out.println(line)所以我知道有些事情是正确的。我无法使用文本文件中的行填充列表。上面的代码告诉我cannot add containers parent to self.

试图找到更多信息只会让我更加困惑。我遇到过一些地方,说jLists比这更复杂?

2 个答案:

答案 0 :(得分:5)

存在许多错误,对所有错误的评论太多:

1)Basic I/O

2)Exceptions

3)How to Use Lists

4)Examples

    BufferedReader in = null;
    String line;
    DefaultListModel listModel = new DefaultListModel();
    try {
        in = new BufferedReader(new FileReader("C:\\users\\me\\desktop\\blah.txt"));
        while ((line = in.readLine()) != null) {
            listModel.addElement(line); //(String.valueof(line));
        }
    } catch (IOException ex) {
        Logger.getLogger(Frame2.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (in != null) {
            in.close();
        }
    }
    JList jList1 = new JList(listModel);

答案 1 :(得分:2)

你真的不能这样做: 再次阅读这一行:jList1.add(line, jList1);你的意思是什么?你正在将jList1添加到jList1,对吧?检查代码并相应地修复它。

相关问题