1

我正在尝试从我的 GUI 应用程序中创建一个简单的实用程序,用于从网站获取数据。特别是其中一个网站的加载时间非常长。所以我决定最好使用 ProgressMonitorInputStream 来通知用户我的程序没有简单地冻结。但是,我一直遇到它阻止 EDT 的问题。为了解决这个问题,我添加了一个 SwingWorker,但现在程序根本无法显示 ProgressMonitor 更新。我究竟做错了什么?

private static String urlToTextLong(URL url) throws IOException{
    final URLConnection urlConn = url.openConnection(); //Open connection
    //Adding header for user agent is required. Otherwise, Google rejects the request
    urlConn.addRequestProperty("User-Agent", 
            "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0"); 

    final StringBuilder buf = new StringBuilder();
    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>(){
        protected Void doInBackground() throws Exception
        {
            ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(null, "Loading", urlConn.getInputStream());
            final Reader r = new java.io.InputStreamReader(pmis, Charset.forName("UTF-8"));//Gets Dta Converts to string
            pmis.getProgressMonitor().setMaximum(urlConn.getContentLength());
            pmis.getProgressMonitor().setMillisToPopup(1);
            pmis.getProgressMonitor().setMillisToDecideToPopup(1);
            while (true) {//Reads String from buffer
                int ch = r.read();
                if (ch < 0)
                    break;
                buf.append((char) ch);
            }
            pmis.close();
            r.close();
            return null;
        }
    };
    worker.execute();
    while(!worker.isDone()){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    String str = buf.toString();
    return str;
}
4

0 回答 0