1
我想动态添加元素到我的DefaultListModel
/JList
,但该列表需要先清空。我打开一个对话窗口。我的问题是,当我使用model.removeAllElements()
时,我的对话框窗口再次出现多次。我究竟做错了什么?如何将元素动态添加到JList/DefaultListModel
我也试过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()
:当用户点击它连接到一个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);
}
}