在Swing Java中向JList添加元素 [英] Adding elements to JList in Swing Java
问题描述
我有一个单击按钮时执行的功能。假设有一个循环将1到10加到 JList
。我将该数据添加到 DefaultListModel
。它完美地运行并且数字被添加。然后我在循环中添加了一个 Thread.sleep(1000)
。但输出是不同的。我想每秒添加1个元素。但现在它等待10秒,并在第10秒结束时将所有1到10加在一起。我在哪里错了?
I have a function that executes when a button is clicked. Suppose there is a loop to add 1 to 10 to a JList
. I add that data to DefaultListModel
. It works perfectly and the numbers get added. Then I added a Thread.sleep(1000)
within the loop. But the output is different. I wanted to add 1 element every second. But now it waits for 10secs and the add all 1 to 10 together at the end of 10th second. Am I wrong anywhere?
List processList = listNumbers.getSelectedValuesList();
DefaultListModel resultList = new DefaultListModel();
listResult.setModel(resultList);
for (int i = 0; i < processList.size(); i++) {
resultList.addElement(String.valueOf(i));
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
}
}
推荐答案
您应该在单独的线程中更新列表,否则最终会阻止事件派发线程。
You should update your list in a separate thread otherwise you end up blocking the event dispatch thread.
尝试以下:
final DefaultListModel model = new DefaultListModel();
final JList list = new JList(model);
//another thread to update the model
final Thread updater = new Thread() {
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
for (int i = 0; i < 10; i++) {
model.addElement(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
};
updater.start();
这篇关于在Swing Java中向JList添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!