【发布时间】:2014-06-12 16:03:40
【问题描述】:
我有一个 SwingWorker 线程,我用它来更新 UI JLabel,除了 publish()/process() 方法之外,程序还可以工作(因为 JLabel 已成功发布并带有适当的文本/背景/边界等)。但是,我想使用 process() 方法将 JLabel 的文本设置为“正在连接...”,而 doInBackground() 执行它的工作,但我的程序中的 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 的功能也符合我的喜好。提前致谢!
【问题讨论】:
标签: java multithreading process publish swingworker