我正在尝试用名称填充JList,这些名称最终将添加到AddressBook GUI中。我想我的逻辑是,创建JList,通过一个从文本文件中读取名称的方法填充它,然后将该JList添加到我的面板中。
我的文本文件如下:
Family,Homer Simpson,111 Homer Drive,Springfield,IL,383838,。。。。
它读取文件的代码如下所示:
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)
{
}
}
我知道我的代码有问题,因为我在这里得到了NullPointerExceptionString [] name = sep.split (",");
。有人能为我指明正确的方向吗?在我成功地读到这个名字后,我该如何将其添加到JList中?谢谢
编辑:
因此,我改变了我的方法,返回一个ArrayList而不是void,并使用以下内容填充JList:
model = new DefaultListModel();
for (int i = 1; i < readContacts().size(); i++)
{
model.addElement(i);
}
nameList = new JList (model);
add(nameList);
但它只是打印出1-10,而不是名字。我想这是因为我使用size()
而不是其他东西,有什么建议吗?
while ((buffer.readLine()) != null) { // read a line once and check it's not null
String sep = buffer.readLine(); // read the following line
您在每次迭代中读取两行。只需阅读一篇:
String sep;
while ((sep = buffer.readLine()) != null) {