无法想出这个。使用worker或invokeLater,UI仍然会冻结。下载每个文件后,我想要更新JList。但JList只会在胎面返回后更新。
以下是代码:
public class MyUi extends javax.swing.JFrame{
...
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt){
SwingUtilities.invokeLater(new Runnable() {
//To get out of the event tread
public void run() {
dl();
}
});
}
private void dl(){
...
//ini and run the download class
Download myDownload = new Download();
myDownload.doDownload(myDlList);
}
public void updateJlist(String myString){
myModel.addElement(myString);
jList1.repaint();
}
}
public class Download{
...
public void doDownload(String[] fileName){
for(int i=0; i<fileName.length; i++){
...//download action...
//for my jList1 to be updated after each file.
MyUi.updateJlist(fileName[i]);
}
}
}
任何例子都会有所帮助。
答案 0 :(得分:4)
invokeLater
与您期望的完全相反 - 它在EDT上运行操作,这解释了行为。
答案 1 :(得分:3)
在后台线程上下载文件,并在updateJlist()
中仅包装Runnable
。
SwingWorker
会更可靠。
附录:正如@mre所说,SwingWorker
还可以轻松报告中期结果,如here所示。
答案 2 :(得分:0)
我创建了一个WorkerThread类来处理Threads和GUI current / main thread。我已经将我的GUI应用程序放在WorkerThread的construct()方法中,当一个事件触发启动XXXServer然后所有线程都被激活并且GUI工作平稳地没有冻结。看看。
/ ** *行动事件* * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)* /
public void actionPerformed(ActionEvent ae){ log.info(&#34; actionPerformed begin ...&#34; + ae.getActionCommand());
try {
if (ae.getActionCommand().equals(btnStart.getText())) {
final int portNumber = 9990;
try {
WorkerThread workerThread = new WorkerThread(){
public Object construct(){
log.info("Initializing the Server GUI...");
// initializing the Server
try {
xxxServer = new XXXServer(portNumber);
xxxServer.start();
btnStart.setEnabled(false);
} catch (IOException e) {
// TODO Auto-generated catch block
log.info("actionPerformed() Start button ERROR IOEXCEPTION..." + e.getMessage());
e.printStackTrace();
}
return null;
}
};workerThread.start();
} catch (Exception e) {
log.info("actionPerformed() Start button ERROR..." + e.getMessage());
e.printStackTrace();
}
} else if (ae.getActionCommand().equals(btnStop.getText())) {
log.info("Exit..." + btnStop.getText());
closeWindow();
}
} catch (Exception e) {
log
.info("Error in ServerGUI actionPerformed==="
+ e.getMessage());
}
}