简体   繁体   中英

Attempting to add items to jList from txt File

I have the following try catch block that executes on a button click.

  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);
  }

I can successfully System.out.println(line) so I know something is working right. I am unable to populate the list with the lines from the text file. The above code tells me I cannot add containers parent to self.

Attempting to find more information has only confused me more. I have come across some places that say jLists are more complciated than this?

There are many mistakes present, too many to comment on all of them:

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);

You really cannot do it: Read again this line: jList1.add(line, jList1); What did you really mean? You are adding jList1 to jList1, right? Check the code and fix it accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM