我想动态添加元素到我的DefaultListModel
/JList
,但列表需要先清空。我打开一个对话窗口。我的问题是,当我使用model.removeAllElements()
我的对话框窗口重新出现多次。我做错了什么?
我也尝试了model.addElementAt(index)
绕过model.removeAllElements()
,但结果是一样的。
private javax.swing.JList serviceList;
serviceList.setModel(model);
serviceList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
serviceList.setLayoutOrientation(javax.swing.JList.HORIZONTAL_WRAP);
serviceList.setSelectionBackground(java.awt.Color.white);
serviceList.setVisibleRowCount(3);
serviceList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
serviceListValueChanged(evt);
}
});
private void serviceListValueChanged(javax.swing.event.ListSelectionEvent evt) {
showTasksDialog();
}
showTasksDialog()
:打开一个对话框窗口与3个按钮,当用户点击第一个它连接到一个URL,然后列表由filllst()
更新。
public void showTasksDialog() {
int selection = serviceList.getSelectedIndex();
Object[] options = {"Analyse", "Build", "Stop"};
int n = taskDialog.showOptionDialog(this,
"What should this Service do?",
"",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
null);
if (n == 0) {
try {
connection.setSlaveToAnalyse(serviceURLJSONArray.getString(selection));
filllist();
} catch (JSONException | IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
filllist()
:应该从我的默认列表中删除所有元素并重新填充它,但如果我使用model.removeAllElements()
,对话框窗口重新出现多次。当我不使用removeAllElements
然后一切都很好,但列表不清空
public void filllist() throws JSONException, IOException {
model.removeAllElements();
serviceURLJSONArray = connection.getSlaves();
for (int i = 0; i < serviceURLJSONArray.length(); i++) {
String slaveStatus = new Connection().getSlaveStatus(serviceURLJSONArray.getString(i));
model.addElement("Service " +(i+1)+" "+slaveStatus);
}
}
在删除和添加元素之前从列表中删除侦听器(或禁用它们),然后在完成后重新添加侦听器。
。
public void filllist() throws JSONException, IOException {
// remove all listeners
ListSelectionListener[] listeners = serviceList.getListSelectionListeners();
for (ListSelectionListener l : listeners) {
serviceList.removeListSelectionListener(l);
}
// do your work
model.removeAllElements();
serviceURLJSONArray = connection.getSlaves();
for (int i = 0; i < serviceURLJSONArray.length(); i++) {
String slaveStatus = new Connection().getSlaveStatus(serviceURLJSONArray.getString(i));
model.addElement("Service " +(i+1)+" "+slaveStatus);
}
// add them back
for (ListSelectionListener l : listeners) {
serviceList.addListSelectionListener(l);
}
}