[英]Populating JList from another method that reads a text file
I'm trying to populate a JList with names which ultimately will be added to an AddressBook GUI. 我正在尝试使用最终将被添加到AddressBook GUI的名称填充JList。 I think I have the logic down which is, create the JList, populate it through a method which has read the names in from a text file, then add that JList to my panel.
我认为我的逻辑是,创建JList,通过从文本文件中读取名称的方法填充它,然后将该JList添加到我的面板中。
My text file looks like this: 我的文本文件如下所示:
Family, Homer Simpson, 111 Homer Drive, Springfield, IL, 383838,.... Family,Homer Simpson,111 Homer Drive,Springfield,IL,383838,....
The code in which it reads the file looks like this: 它读取文件的代码如下所示:
private void readContacts() { File cFile = new File ("Contacts.txt"); BufferedReader buffer = null; ArrayList <String> contact = new ArrayList<String>(); try { buffer = new BufferedReader (new FileReader (cFile)); String text; while ((buffer.readLine()) != null) { String sep = buffer.readLine ( ); String [] name = sep.split (","); text = name[1]; contact.add(text); System.out.println (text); } } catch (FileNotFoundException e) { } catch (IOException k) { } }
I know i'm doing something wrong with the code, because I'm getting NullPointerException here String [] name = sep.split (",");
我知道我的代码做错了,因为在这里我得到了NullPointerException
String [] name = sep.split (",");
. 。 Can anyone point me in the right direction, and after I successfully read the name in, how would I add that to a JList?
谁能指出我的正确方向,并且在我成功读取名称后,如何将其添加到JList中? Thanks.
谢谢。
EDIT: 编辑:
So, i've changed my method to return an ArrayList instead of void, and to populate the JList i'm using this: 因此,我更改了方法以返回ArrayList而不是void,并使用以下方法填充JList:
model = new DefaultListModel(); for (int i = 1; i < readContacts().size(); i++) { model.addElement(i); } nameList = new JList (model); add(nameList);
but it's just printing it out 1-10 as opposed to the the names. 但是它只是将其打印出来,而不是名称。 I'm assuming it's because I'm using
size()
instead of something else, any suggestions? 我假设这是因为我使用
size()
而不是其他东西,有什么建议吗?
while ((buffer.readLine()) != null) { // read a line once and check it's not null
String sep = buffer.readLine(); // read the following line
You're reading two lines at each iteration. 您每次迭代都读取两行。 Just read one:
只需阅读一个:
String sep;
while ((sep = buffer.readLine()) != null) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.