是的,您可以使用一个
SwingWorker想法,即一个任务需要花费大量时间在单独的线程(后台线程)中运行,因此您不会阻塞gui,并且Jframe不会冻结。这是一个完整的示例,我非常喜欢Swing
Worker示例。
基本上以示例为例,您将创建自己的扩展
SwingWorker覆盖的类
doInBackground。
注意:您可以具有类似普通班级的字段。
范例:
class Worker extends SwingWorker<Void, String> { private SomeClass businessDelegate; private JLabel label; @Override protected Void doInBackground() throws Exception { //here you make heavy task this is running in another thread not in EDT businessDelegate.callSomeService(); setProgress(30); // this is if you want to use with a progressBar businessDelegate.saveToSomeDatabase(); publish("Processes where saved"); return null; } @Override protected void process(List<String> chunks){ //this is executed in EDT you can update a label for example label.setText(chunks.toString()); } //add setters for label and businessDelegate }您还了解了
process(..)
publish(..)和
done()。
并在您的客户端代码中放入。
SwingWorker<Void,String> myWorker = new Worker();myWorker.execute();



