zoukankan      html  css  js  c++  java
  • 使用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("
    ");
    				}
    				reader.close();
    				return builder;
    			}
    
    			@Override
    			protected void process(List<String> chunks) {
    				for (String line:chunks) {
    					textArea.append(line);
    					textArea.append("
    ");
    				}
    				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();
    	}
    
  • 相关阅读:
    MyBatis动态SQL语句
    MyBatis分页
    理解 Linux 的处理器负载均值
    Linux命令之du
    Linux命令之df
    Linux命令之lsof
    maven打包加时间戳
    多线程学习-ListenableFuture使用介绍以及示例
    Host is not allowed to connect to this MySQL server解决方法
    Dapper,大规模分布式系统的跟踪系统
  • 原文地址:https://www.cnblogs.com/zhhy236400/p/10555318.html
Copyright © 2011-2022 走看看