我正在尝试使用最终将添加到 AddressBook GUI 中的名称填充 JList。我认为我的逻辑是,创建 JList,通过从文本文件读取名称的方法填充它,然后将该 JList 添加到我的面板中。
我的文本文件如下所示:
家庭,荷马辛普森,111 Homer Drive,斯普林菲尔德,伊利诺伊州,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)
{
}
}
我知道我的代码出了问题,因为我在这里遇到 NullPointerException String [] 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) {
关于java - 从读取文本文件的另一个方法填充 JList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29989609/