0
我目前正在開發一個使用Apache的http API的HTTP應用程序,我正在使用GUI。在每次GET或POST請求之後,我想用一些消息更新GUI TextArea。問題是這些消息在所有請求完成後纔會出現。Java Apache httpclient阻止GUI
我還注意到,如果我在每次請求後在控制檯上寫入消息,則會出現消息,但如果我在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");
}
}
誰能幫我解決這個問題?謝謝! }
但是我在另一個線程中發出http請求...而你通過「通知GUI線程更新UI」是什麼意思。我怎樣才能做到這一點? –
你是否在'SendGetReq#run()'方法中的任何內容上同步?這可能會阻止'GUI#setText()'方法。 –
我想通了...終於...謝謝! –