我有这段代码,它创建了一个列表:
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);
当我从该列表中选择对象时,我有一个按钮,可以删除所选对象:
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);
}
});
但是在删除对象之后,当我尝试将新对象添加到构成列表的同一个数组时,它将不再显示列表中的更改。
答案 0 :(得分:2)
下面:
//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;
为什么你有很多阵列,如nameData[]
,emailData[]
等?不要更好地创建一个类来保存这个信息吗?例如:
class Data {
String name;
String email;
Date dateOfBirth;
String address;
public Data(String name, String email, Date dateOfBirth, String address){ ... }
// getters and setters here
}
然后在您的列表模型中,您可以添加Data
这样的对象:
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));
请仔细阅读 How to Use Lists 教程。这是你的朋友。