How can I pass arguments into SwingWorker?

2019-04-28 03:56发布

问题:

I'm trying to implement Swing worker in my GUI. At the moment I have a JFrame containing a button. When this is pressed it should update a tab displayed and then run a program in the background thread. Here is what I have so far.

class ClassA
{
    private static void addRunButton() 
    {
        JButton runButton = new JButton("Run");
        runButton.setEnabled(false);
        runButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) 
            {
                new ClassB().execute();
            }
    });

    mainWindow.add(runButton);
    }
}

class ClassB extends SwingWorker<Void, Integer>
{
    protected Void doInBackground()
    {
        ClassC.runProgram(cfgFile);
    }

    protected void done()
    {
        try 
        { 
        tabs.setSelectedIndex(1);
        } 
        catch (Exception ignore) 
        {
        }
    }
}

I don't understand how I can pass in my cfgFile object though. Please can someone advise on this?

回答1:

Why not give it a File field and fill that field via a constructor that takes a File parameter?

class ClassB extends SwingWorker<Void, Integer>
{
    private File cfgFile;

    public ClassB(File cfgFile) {
       this.cfgFile = cfgFile;
    }

    protected Void doInBackground()
    {
        ClassC.runProgram(cfgFile);
    }

    protected void done()
    {
        try 
        { 
        tabs.setSelectedIndex(1);
        } 
        catch (Exception ignore) 
        {
           // *** ignoring exceptions is usually not a good idea. ***
        }
    }
}

And then run it like so:

public void actionPerformed(ActionEvent e) 
{
    new ClassB(cfgFile).execute();
}


回答2:

Use constructor to pass the parameter. For example, like this:

class ClassB extends SwingWorker<Void, Integer> 
{

private File cfgFile; 

public ClassB(File cfgFile){
this.cfgFile=cfgFile;
}

protected Void doInBackground() 
{ 
    ClassC.runProgram(cfgFile); 
} 

protected void done() 
{ 
    try  
    {  
    tabs.setSelectedIndex(1); 
    }  
    catch (Exception ignore)  
    { 
    } 
} 

}