I'm trying to update the JList by deleting a contact and its not updating the JList like I wanted it to.
Originally, the JList would look like this.
Broadcast //Not allowed to delete this element
Andy
Bobby
Chris
Brad
Assuming that I have deleted Andy off the list using a button. It should show
Broadcast //Not allowed to delete this element
Bobby
Chris
Brad
Instead it shows this on the JList.
contact0
contact2
contact3
contact4
I don't know what went wrong and I looked in many sources. I want it to return the actual names, not the contact#. Code is below.
private JList<String> listContacts;
private DefaultListModel<String> model;
private String[] contactList;
model = new DefaultListModel<String>();
contactList = controller.getContacts();
for(String contact : contactList){
model.addElement(contact);
}
listContacts = new JList<String>();
listContacts.setModel(model);
class MyButtonListener5 implements ActionListener{
public void actionPerformed(ActionEvent e){
if(listContacts.getSelectedIndex() == 0){
controller.displayMsg("Can't delete broadcast.\n");
}
else if(listContacts.getSelectedIndex() > 0){
controller.displayMsg("You tried to delete " + listContacts.getSelectedValue() +".\n");
model.remove(listContacts.getSelectedIndex());
listContacts.setModel(model);
}
else{
controller.displayMsg("No contact to delete. Please select one.\n");
}
}
}
This is for contactList to getContacts. This method is in the controller class. I hope this clarifies why I'm having trouble.
public String[] getContacts(){
Contact[] contacts = new Contact[5];
String[] names = new String[5];
for(int i = 0; i < 5; i++){
contacts[i] = new Contact("contact" + i);
names[i] = contacts[i].getName();
}
return names;
}
This is in my Contact Class.
private String name;
private String nickname;
public Contact(){
name = "";
nickname = "";
}
public Contact(String name){
this.name = name;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
@Override
public String toString(){
return this.getName();
}