sealz
sealz

Reputation: 5408

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?

Upvotes: 0

Views: 3651

Answers (2)

mKorbel
mKorbel

Reputation: 109823

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

Upvotes: 5

AlexR
AlexR

Reputation: 115398

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.

Upvotes: 2

Related Questions