简体   繁体   English

SwingWorker:如何将值从process()方法委托给另一个类

[英]SwingWorker: How to delegate values from the process() method to another class

In my program I have a swingworker, so that the user can access the GUI while the program itself is still running. 在我的程序中,我有一个swingworker,以便用户可以在程序本身仍在运行时访问GUI。

Is there a way to return the values I declare in the process() method to another class? 有没有办法将我在process()方法中声明的值返回给另一个类? The reason I ask is the following: 我问的原因如下:

The GUI shows among other things charts, which should update if the user pushes on a button. GUI会显示其他图表,如果用户按下按钮,图表应会更新。 Within the doInBackground() method an ArrayList is permanent updated. doInBackground()方法中,将永久更新ArrayList。 In this ArrayList are values that the charts should show, so every time the user pushes the button the chart should show the values that are actually in the Array List 在此ArrayList中是图表应显示的值,因此,每当用户按下按钮时,图表应显示实际在Array List中的值

The code is the following 代码如下

 protected Void doInBackground()
{
    SaveList savelist = new SaveList();


    while(true)
    {
     try
     {
            savelist.updateSaveList();
            publish((SaveList) savelist);

            Thread.sleep(100);
     }

     catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}



    protected void process(SaveList savelist) 
    {
     this.savelistsize = savelist.saveListSize();
     this.trueLabeled = savelist.trueLabeled();
     this.falseLabeled = savelist.falseLabeled();
     this.trueLabeledPercent = savelist.trueLabeled()/savelist.saveListSize();
     this.falseLabeledPercent = savelist.falseLabeled()/savelist.saveListSize();
    }`

If I understand you correctly, you want to delegate some of the logic done in process() to a different class. 如果我对您的理解正确,则希望将process()完成的某些逻辑委托给另一个类。 In that case make a named subclass of the SwingWorker and initialize it with the delegate instance. 在这种情况下,请创建SwingWorker的命名子类,并使用委托实例对其进行初始化。

Example: 例:

public class MySwingWorker extends SwingWorker<Void, X> { // X - I don't know the type of SaveList elements

    private MyDelegate delegate;

    public MySwingWorker(MyDelegate delegate) {
        this.delegate = delegate;
    }

    protected Void doInBackground() { ... }

    protected void process(SaveList savelist) {
        delegate.doSomethingWith(savelist);
    }
}

and you can then implement your logic in MyDelegate.doSomethingWith(SaveList) 然后可以在MyDelegate.doSomethingWith(SaveList)实现您的逻辑

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM