Sam
Sam

Reputation: 21

Can't populate a JList from a TXT File

Here's my working code that reads a TXT File and shows it in the console:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.DefaultListModel;
import javax.swing.JList;

public class LeerArchivoDeTexto {
    public static void main(String[] args) {
        File archivo = new File("Archivo.txt");
        BufferedReader lector = null;
        DefaultListModel lista = new DefaultListModel();
        JList jList1 = new JList();

        try {
            lector = new BufferedReader(new FileReader(archivo));
            String texto = null;

            while ((texto = lector.readLine()) != null) {
                lista.addElement(texto);
                System.out.println(texto);
            }
            jList1.setModel(lista);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (lector != null) {
                    lector.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

The thing is that I want to load the data I have in my TXT File to a JList. The commented lines which envolve the JList aren't working. Any ideas?

Upvotes: 2

Views: 1520

Answers (3)

janhink
janhink

Reputation: 5023

The JList is not instantiated because you explicitly set it to null:

JList JList1 = null; // not initialized

So when trying to set the model to it I assume you get a NullPointerException on this line:

JList1.setModel(lista); // NPE here

You need to instantiate the JList and set the model to it like this:

JList jList1 = new JList();
jList1.setModel(lista);

Upvotes: 6

jzd
jzd

Reputation: 23629

You never create a new instance of a JList that is asigned to JList1, yet you are trying to call a method on that variable and most likely get a NullPointerException.

Instead of assigning null to JList1, assign a new instance.

Upvotes: 1

Howard
Howard

Reputation: 39197

If you constract the JList correctly via

JList JList1 = new JList();

you can uncomment all your lines and it will work fine. Of course you then have to add this list to a swing container.

Upvotes: 1

Related Questions