javaapachehttpclient阻塞GUI
我目前正在使用Apache的HTTP API开发一个HTTP应用程序,并且正在使用GUI。在每次GET或POST请求之后,我想用一些消息更新GUI文本区域。问题是,这些消息在所有请求完成后出现 我还注意到,如果我在每次请求之后在控制台上写消息,消息就会出现,但是如果我在GUI上写消息,所有消息都会出现在最后 以下是一些代码片段: GUI构造函数:javaapachehttpclient阻塞GUI,java,apache,httpclient,block,Java,Apache,Httpclient,Block,我目前正在使用Apache的HTTP API开发一个HTTP应用程序,并且正在使用GUI。在每次GET或POST请求之后,我想用一些消息更新GUI文本区域。问题是,这些消息在所有请求完成后出现 我还注意到,如果我在每次请求之后在控制台上写消息,消息就会出现,但是如果我在GUI上写消息,所有消息都会出现在最后 以下是一些代码片段: GUI构造函数: public GUI() { initComponents(); SetMessage.gui = this; }
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请求类(每个请求都由一个线程发出):
和HttpConnection类(该类的实例是在我按下GUI上的按钮时创建的):
哦!!以及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");
}
}
有人能帮我解决这个问题吗?谢谢
}是的,GUI的标准行为。您需要在另一个线程中执行HTTP请求,然后通知GUI线程更新UI。Swing尤其需要从单个线程更新UI,事件调度线程要精确
请参阅
SwingUtilities#isEventDispatchThread()
,SwingUtilities#invokeLater()
和SwingWorker
类。但我在另一个线程中发出http请求。。。“通知GUI线程更新UI”是什么意思。我该怎么做?在SendGetReq\run()
方法中是否同步任何内容?这可能会阻塞GUI\setText()
方法。。。最后非常感谢。
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();
}
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");
}
}