disposing frame from swingWorker

左心房为你撑大大i 提交于 2019-12-20 04:03:07

问题


actually i have called the swing worker from a frame (Suppose) A.. in the swing worker class in do-in-Background method i have certain db queries and i am calling frame B too.. in the done() method however i want to dispose the frame A.. how can i do that..? i cannot write dispose() in frame A class because that results in disposing of frame before the new frame(frame B) is visible... Please help!!

class frameA extends JFrame{
public frameA(){
//done some operations..
SwingWorker worker=new Worker();
       worker.execute();

}
public static void main(string[] args){
  new frameA();
}

}

and in worker class

class Worker extends SwingWorker<Void, String> {



public Worker() {
    super();


}

//Executed on the Event Dispatch Thread after the doInBackground method is finished
@Override
protected void done() {
    //want to dispose the frameA here..


}

@Override
protected Void doInBackground() throws Exception {
    // some db queries
  new frameB().setVisible(true);  
  // call to frameb
}

回答1:


  1. The done() method of the SwingWorker is usually overridden to display the final result. Upon completion of doInBackground() , the SwingWorker automaticlly invokes done() in the EDT. So put your frame's invisible and visible code in this function.

  2. The doInBackground() is not meant to do any GUI rendering task. You can invoke publish(V) from doInBackground() function which in turn invokes The process(V) method to run inside the EDT and performing GUI rendering task.

So a sample solution would be:

class Worker extends SwingWorker<Void, String> {

  JFrame frameA;

  public Worker(JFrame frameA) {
    this.frameA = frameA;

  }

  @Override
  protected void done() {
    frameA.dispose();
    new frameB().setVisible(true); 

  }
  //other code
}

Now, create you SwingWorker instance by passing the target frame to it's constructor: new Worker(frame); For your context you probably could make use of this

However, you should not really design your application to be dependent on multiple JFrame. There are reasons for not to use multiple JFrame window. For more, see The Use of Multiple JFrames, Good/Bad Practice?. A general work around with use case where multiple frame would be needed is explained here.



来源:https://stackoverflow.com/questions/19976430/disposing-frame-from-swingworker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!