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);
}
}