Java Apache httpclient阻止GUI

时间:2011-08-23 09:55:56

标签: java apache httpclient block

我目前正在使用Apache的http API开发HTTP应用程序,而我正在使用GUI。在每次GET或POST请求之后,我想用一些消息更新GUI TextArea。问题是在完成所有请求后会出现这些消息。

我还注意到,如果我在每次请求后在控制台上写消息,则会显示消息,但如果我在GUI上写入,则所有消息都会显示在最后。

以下是一些代码段:

GUI构造函数:

public GUI() {
        initComponents();
        SetMessage.gui = this;
}

SetMessage类:

public class SetMessage implements Runnable{

    public static GUI gui;
    private String msg;

    public SetMessage( String msg){
        synchronized(gui){
            this.msg = msg;
        }
    }

    public void run() {
        gui.setText(msg);
    }

}

GET请求类(每个请求都由一个线程完成):

public class SendGetReq extends Thread {

private HttpConnection hc = null;
private DefaultHttpClient httpclient = null;
private HttpGet getreq = null;
private int step = -1;
private String returnString = null;

public SendGetReq(HttpConnection hc, DefaultHttpClient httpclient, HttpGet getreq, int step) {
    this.hc = hc;
    this.httpclient = httpclient;
    this.getreq = getreq;
    this.step = step;
}

@Override
public void run() {
   // CODE
}

和HttpConnection类(当我按下GUI上的按钮时创建此类的实例):

    public class HttpConnection {
        private DefaultHttpClient httpclient = null;
        private HttpGet getreq = null;
        private HttpPost postreq = null;
private SendGetReq tempGet = null;
         // More fields
        private void RandomMethod(){
//Initialize getreq
(tempGet = new SendGetReq(this, httpclient, getreq, 0)).start();
new SetMessage("Message").run();

}

哦! GUI的SetText方法:

public synchronized void setText(String msg){
        if(!"".equals(msg)){
            Date currentDate = new Date();
            Calendar calendar = GregorianCalendar.getInstance();
            calendar.setTime(currentDate);
            jTextArea1.append(calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE)+":"+calendar.get(Calendar.SECOND)+" --- "+msg+"\n");                        
        }
    }

任何人都可以帮我解决这个问题吗?谢谢!     }

1 个答案:

答案 0 :(得分:1)

是的,GUI的标准行为。您需要在另一个线程中执行HTTP请求,然后通知GUI线程更新UI。 Swing特别要求从单个线程更新UI,事件调度线程是精确的。

请参阅SwingUtilities#isEventDispatchThread()SwingUtilities#invokeLater()SwingWorker类。