The*_*imp 6 java swing swingworker argument-passing
我正在尝试在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<Void, Integer>
{
protected Void doInBackground()
{
ClassC.runProgram(cfgFile);
}
protected void done()
{
try
{
tabs.setSelectedIndex(1);
}
catch (Exception ignore)
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白我怎么能传递我的cfgFile对象.有人可以就此提出建议吗?
Hov*_*els 20
为什么不给它一个文件字段并通过带有File参数的构造函数填充该字段?
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. ***
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后运行它:
public void actionPerformed(ActionEvent e)
{
new ClassB(cfgFile).execute();
}
Run Code Online (Sandbox Code Playgroud)