简体   繁体   English

无法从TXT文件填充JList

[英]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: 这是我的工作代码,它读取TXT文件并在控制台中显示:

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 . 问题是我想将我的TXT文件中的数据加载到JList The commented lines which envolve the JList aren't working. 包含JList的注释行无效。 Any ideas? 有任何想法吗?

The JList is not instantiated because you explicitly set it to null: JList未实例化,因为您明确将其设置为null:

JList JList1 = null; // not initialized

So when trying to set the model to it I assume you get a NullPointerException on this line: 因此,当尝试将模型设置为它时,我假设您在此行上获得NullPointerException

JList1.setModel(lista); // NPE here

You need to instantiate the JList and set the model to it like this: 您需要实例化JList并将模型设置为它,如下所示:

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

If you constract the JList correctly via 如果你通过正确构造JList

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. 当然,您必须将此列表添加到swing容器中。

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 . 您永远不会创建一个与JList1JList的新实例,但是您尝试在该变量上调用方法,并且很可能会获得NullPointerException

Instead of assigning null to JList1 , assign a new instance. 而不是为JList1分配null, JList1分配一个新实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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