Java SwingWorker已扩展,但GUI仍处于冻结状态
这是我第一次尝试将Swing组件用于GUI,我正在尝试实现一个允许用户运行2个异步远程命令的解决方案 简而言之,这两个命令是:Java SwingWorker已扩展,但GUI仍处于冻结状态,java,swing,user-interface,worker,Java,Swing,User Interface,Worker,这是我第一次尝试将Swing组件用于GUI,我正在尝试实现一个允许用户运行2个异步远程命令的解决方案 简而言之,这两个命令是: 在远程服务器上执行命令 下载数据 我的问题是,虽然我雇佣了一个摇摆工人,但我的主菜单仍然冻结。此外,在添加第一个命令之前,将传递SwingWorker并执行第二个命令 我已经在网上浏览了很多很多的例子和解释,我觉得我仍然缺少一些关键的直觉,这些直觉可以让我成功 我的swing worker有什么问题,因为它仍然会冻结GUI,并且不会等到完成后再执行其余的代码 编辑:最终
public TestGUI(){
//code to show Gui with buttons
//code also contains mouse listener:
btn.addMouseListener(new MouseAdapter() { // listener
@Override
public void mousePressed(MouseEvent e){
SampleClass.doRemoteTask();
}
});
}
示例类-在后台使用Swing Worker运行远程命令
public SampleClass(){
public static void doRemoteTask(){
//create sample worker
final SampleWorker sampleworker = new SampleWorker(command, session);
//add change listener to wait for state change.
sampleworker.addPropertyChangeListener(new PropertyChangeListener(){
@Override
public void propertyChange(PropertyChangeEvent event) {
if(StateValue.DONE == sampleworker.getState()){
try {
Integer i = sampleworker.get();
} catch (InterruptedException | ExecutionException e) {
System.out.println("Could not get");
e.printStackTrace();
}
};
}
});
//do other stuff after the state DONE
sampleworker.execute(); //sample worker is a long task. This is why it was created in the Swing Worker.
}
}
protected Integer doInBackground() throws Exception {
byte[] tmp=new byte[1024];
int j = 0;
publish("Start");
while(true){
//do stuff
if(j % 100 == 0){
setProgress(j);
}
//write to System.out then exit
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
publish("Completed");
return j;
}
示例工人类-在后台运行命令
public SampleClass(){
public static void doRemoteTask(){
//create sample worker
final SampleWorker sampleworker = new SampleWorker(command, session);
//add change listener to wait for state change.
sampleworker.addPropertyChangeListener(new PropertyChangeListener(){
@Override
public void propertyChange(PropertyChangeEvent event) {
if(StateValue.DONE == sampleworker.getState()){
try {
Integer i = sampleworker.get();
} catch (InterruptedException | ExecutionException e) {
System.out.println("Could not get");
e.printStackTrace();
}
};
}
});
//do other stuff after the state DONE
sampleworker.execute(); //sample worker is a long task. This is why it was created in the Swing Worker.
}
}
protected Integer doInBackground() throws Exception {
byte[] tmp=new byte[1024];
int j = 0;
publish("Start");
while(true){
//do stuff
if(j % 100 == 0){
setProgress(j);
}
//write to System.out then exit
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
publish("Completed");
return j;
}
SampleClass.doRemoteTask()代码>我们不知道该方法的作用。该方法在EDT上调用,如果调用长时间运行的代码,可能会导致GUI冻结;在远程服务器上调用耗时的命令。我将编辑我的帖子,详细说明命令的类型以及进程挂起的位置。这正是导致GUI冻结的原因。该方法应该启动SwingWorker,SwingWorker将调用远程服务器上的命令。