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 != nu开发者_JAVA技巧ll) {
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?
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);
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.
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.
精彩评论