8

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?

2 Answers2

23

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();
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
1

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)  
    { 
    } 
} 

}

carawan
  • 508
  • 3
  • 10
  • I'm not user this variation adds anything to @Hovercraft's earlier [answer](http://stackoverflow.com/questions/7895428/how-can-i-pass-arguments-into-swingworker/7895454#7895454). – trashgod Oct 25 '11 at 20:52
  • 1
    Sorry. Time time gap between these two answers was very short. First answer was submitted when I am preparing my answer without being aware of it. – carawan Oct 29 '11 at 04:49