如何将参数传递给SwingWorker?

我正在尝试在我的GUI中实现Swing worker。 目前我有一个包含按钮的JFrame。 按下此按钮时,它应更新显示的选项卡,然后在后台线程中运行程序。 这是我到目前为止所拥有的。

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 { protected Void doInBackground() { ClassC.runProgram(cfgFile); } protected void done() { try { tabs.setSelectedIndex(1); } catch (Exception ignore) { } } } 

我不明白我如何传递我的cfgFile对象。 有人可以就此提出建议吗?

为什么不给它一个文件字段并通过带有File参数的构造函数填充该字段?

 class ClassB extends SwingWorker { 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. *** } } } 

然后运行它:

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

使用构造函数传递参数。 例如,像这样:

 class ClassB extends SwingWorker { 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) { } } 

}