[英]Refeshing JList Java after add Items
I'm trying to create simple addressbook with Java, I have JList that contain people's name, after successfully create person, the name of person will be show on JList, but it still didn't working. 我正在尝试使用Java创建简单的通讯录,我有包含人名的JList,成功创建人后,人名将显示在JList上,但仍然无法正常工作。
Here's My AddressBookGUI code: 这是我的AddressBookGUI代码:
public class AddressBookGUI extends JFrame {
// GUI components
private DefaultListModel<String> namaPeople = new DefaultListModel<>();
private JList<String> nameList = new JList<>(namaPeople);
public AddressBookGUI() {
JScrollPane listPane = new JScrollPane(nameList);
getContentPane().add(listPane, BorderLayout.NORTH);
}
public static void addPerson(Person info) {
// insert new Person's Name to JList
// ERROR's Here
DefaultListModel<String> namaPeople = new DefaultListModel<>();
namaPeople.addElement(info.getName());
}
}
You try to create a new DefaultListModel
instance in the static
method while you should use which one which exists if you want to add a Person
and not overwriting the existing list. 您尝试在static
方法DefaultListModel
创建一个新的DefaultListModel
实例,而如果要添加一个Person
而不覆盖现有列表,则应使用存在的实例。
Just use the namaPeople
instance field to add it the new Person
. 只需使用namaPeople
实例字段将其添加为新的Person
。
And remove also the static
modifier here : 并在这里也删除static
修饰符:
public static void addPerson(Person info)
because it prevents the method from accessing to a instance field. 因为它阻止方法访问实例字段。
public class AddressBookGUI extends JFrame {
// GUI components
private DefaultListModel<String> namaPeople = new DefaultListModel<>();
private JList<String> nameList = new JList<>(namaPeople);
public AddressBookGUI() {
JScrollPane listPane = new JScrollPane(nameList);
getContentPane().add(listPane, BorderLayout.NORTH);
}
public void addPerson(Person info) {
// insert new Person's Name to JList
namaPeople.addElement(info.getName());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.