Reputation: 296
I have this piece of code, which creates a list:
rightPanel.add(Box.createRigidArea(new Dimension(20, 20)));
final DefaultListModel model = new DefaultListModel();
for(int i=0;i<nameData.length;i++){
if(nameData[i]==null) break;
model.addElement(nameData[i]);
}
final JList list = new JList();
list.setModel(model);
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(new Dimension(250, 80));
listScroller.setAlignmentX(LEFT_ALIGNMENT);
rightPanel.add(listScroller);
When I select the object from that list, I have a button which it makes it possible to delete the selected object:
rightPanel.add(Box.createRigidArea(new Dimension(20, 20)));
final JButton deleteConfirmButton = new JButton("Kustuta");
deleteConfirmButton.setEnabled(false);
rightPanel.add(deleteConfirmButton);
deleteConfirmButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
model.removeElementAt(listIndex);
nameData[listIndex] = null;
deleteConfirmButton.setEnabled(false);
}
});
But after deleting the object, when I'm trying to add a new object to the same array that the list is made of, it won't show the changes in the list anymore.
Upvotes: 1
Views: 99
Reputation: 17971
Here:
//Adds the data from the textfield to corresponding string.
String name = nameTextField.getText();
String eMail = eMailTextField.getText();
String dateOfBirth = dateOfBirthTextField.getText();
String address = addressTextField.getText();
//Stores the string data in an array.
nameData[n] = name;
eMailData[n] = eMail;
dateOfBirthData[n] = dateOfBirth;
addressData[n] = address;
Why do you have plenty of arrays such as nameData[]
, emailData[]
etc ? Don't be better create a class to hold this info instead? For instance:
class Data {
String name;
String email;
Date dateOfBirth;
String address;
public Data(String name, String email, Date dateOfBirth, String address){ ... }
// getters and setters here
}
Then in your list model you can add Data
objects like this:
String name = nameTextField.getText();
String eMail = eMailTextField.getText();
String dateOfBirth = dateOfBirthTextField.getText();
String address = addressTextField.getText();
DefaultListModel model = (DefaultListModel)list.getModel();
model.add(new Data(name, eMail, dateOfBirth, address));
Please take a carefully read to How to Use Lists tutorial. It's your friend.
Upvotes: 2