[英]SwingWorker: process() method is not being called
我有一個SwingWorker線程,我正在使用它來更新UI JLabel,除了publish()/ process()方法之外,該程序還可以工作(因為JLabel已成功發布並帶有適當的文本/背景/邊框等) )。 但是,我想在doInBackground()工作時使用process()方法將JLabel的文本設置為“ Connecting ...”,但是我的程序中從未調用過process()方法(顯然使用publish()方法)。 有什么建議嗎?
這是SwingWorker:
public class PcclientBackgroundWork extends SwingWorker < String, String> {
public JLabel connectionStatus2;
String msg;
/* Constructor */
public PcclientBackgroundWork(JLabel label){
connectionStatus2 = label;
}
/*Background work to determine Application connection status
and pass corresponding message (String msg) to done() */
@Override
public String doInBackground() throws Exception {
String serverName = "localhost"; //UDP is sent within same machine
int port = 6789;
try {
Socket client = new Socket(serverName, port);
BufferedReader in = new BufferedReader
(new InputStreamReader(client.getInputStream()));
while(!in.ready()){
publish("Connecting"); //Want this method called until the bufferedReader is ready.
} //Loops until ready
msg = in.readLine(); //Incoming text is only one line
if(msg.equals("Connection Unsuccessful"))
{
msg = "Application Connection Failed";
} else {
msg = "App Connected " + msg;
}
System.out.println("msg = " + msg);
in.close(); //Close reader
client.close(); //Close client socket
} catch (IOException e) {
e.printStackTrace();
msg = "Application Connection Failed"; //JLabel text set the same as
} //if connection is unsuccessful (lines 66-68)
return msg;
}
public void process(String msg){
System.out.println("process method called...");
connectionStatus2.setText(msg);
}
/*Method to set JLabel information when doInBackground() is complete */
@Override
public void done() {
try {
connectionStatus2.setText(get()); //get() is the return value of doInBackground (String msg)
connectionStatus2.setBorder(BorderFactory.createLineBorder(Color.black));
connectionStatus2.setVisible(true);
connectionStatus2.setOpaque(true);
if(get().equals("Application Connection Failed")){
connectionStatus2.setBackground(Color.PINK);
} else {
connectionStatus2.setBackground(Color.GREEN);
}
} catch (InterruptedException ex) {
} catch (ExecutionException ex) {
Logger.getLogger(PcclientUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
我沒有發布UI線程,因為除了發布/處理方法之外,我喜歡SwingWorker的功能。 提前致謝!
process
的簽名是process(List<V>)
,而不是process(V)
。 將您的處理方法更改為process(List<String> list)
; 您可能會在列表中獲得多個項目,具體取決於在流程有機會運行之前調用發布的頻率。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.