一個比SwingWorker更好的類Swing tip
當我們開發Swing應用程序的時候,SwingWorker是一個非常有用的類。SwingWorker類的目的是實現一個后臺線程,讓你可以用它來執行一些費時的操作,而不阻塞你程序GUI操作。我常用它來實現執行進度提醒。但是這個類有一個很大的缺點,就是假如你沒有在完成方法中調用get()方法,將丟失所有在doInBackground()方法中拋出的異常。可能你的程序還沒有全部執行完就停止了,但卻不知道為什么。而Swing tip是一個能夠很好解決這個問題的類。以下是它的源代碼:
public abstract class BetterSwingWorker { private final SwingWorker原文地址:http://www.baptiste-wicht.com/2010/09/a-better-swingworker/worker = new SimpleSwingWorker(); public void execute() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { before(); } }); worker.execute(); } protected void before() { //Nothing by default } protected abstract void doInBackground() throws Exception; protected abstract void done(); private class SimpleSwingWorker extends SwingWorker { @Override protected Void doInBackground() throws Exception { BetterSwingWorker.this.doInBackground(); return null; } @Override protected void done() { try { get(); } catch (final InterruptedException ex) { throw new RuntimeException(ex); } catch (final ExecutionException ex) { throw new RuntimeException(ex.getCause()); } BetterSwingWorker.this.done(); } } }
本文由用戶 碼頭工人 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!