从 swingWorker 处理框架

2022-01-24 00:00:00 java swing jframe swingworker

实际上我已经从框架(假设)A.. 在 do-in-Background 方法中的 swing 工作人员类中调用了 swing worker,我有某些 db 查询,我也在调用框架 B.. 在 done()方法但是我想处理框架 A.. 我该怎么做..?我不能在框架 A 类中编写 dispose(),因为这会导致在新框架(框架 B)可见之前处理框架......请帮助!

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();
}

}

在工人阶级中

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. SwingWorkerdone() 方法通常被覆盖以显示最终结果.之上doInBackground() 完成后,SwingWorker 自动调用done() 在 EDT 中.所以把你框架的不可见和可见代码放在这个函数中.

  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.

doInBackground() 并不意味着执行任何 GUI 渲染任务.您可以从 doInBackground() 函数调用 publish(V) 函数,该函数又调用 process(V) 方法在 EDT 内运行并执行GUI 渲染任务.

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
}

现在,通过将目标框架传递给它的构造函数来创建您的 SwingWorker 实例:new Worker(frame);对于您的上下文,您可能可以使用 this

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

但是,您不应该真正将您的应用程序设计为依赖于多个 JFrame.有理由不使用多个JFrame 窗口.有关更多信息,请参阅 使用多个 JFrame,好的/坏的做法?.在此解释.

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.

相关文章