使用SwingWorker为界面执行异步任务
当UI界面需要读取网络内容等耗时操作时,可以使用这个方法。
添加按钮的点击事件:
btnRun.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { webRead(); } });
添加webReader方法:
public void webRead() { new SwingWorker<StringBuilder, String>(){ @Override protected StringBuilder doInBackground() throws Exception { URL url=new URL("https://home.firefoxchina.cn/?from=extra_start"); URLConnection connection=url.openConnection(); BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String line; StringBuilder builder =new StringBuilder(); while((line=reader.readLine())!=null) { // publish(line); builder.append(line).append("\n"); } reader.close(); return builder; } @Override protected void process(List<String> chunks) { for (String line:chunks) { textArea.append(line); textArea.append("\n"); } super.process(chunks); } @Override protected void done() { try { textArea.setText(get().toString()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } super.done(); } }.execute(); }