如何将参数传递给SwingWorker? [英] How can I pass arguments into SwingWorker?
本文介绍了如何将参数传递给SwingWorker?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在GUI中实现Swing worker。目前我有一个包含按钮的JFrame。按下此按钮时,它应更新显示的选项卡,然后在后台线程中运行程序。以下是我到目前为止的情况。
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)
{
}
}
}
我不知道如何传递我的 cfgFile
对象。有人可以就此提出建议吗?
I don't understand how I can pass in my cfgFile
object though. Please can someone advise on this?
推荐答案
为什么不给它一个文件字段并通过带文件的构造函数填充该字段参数?
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. ***
}
}
}
然后运行它是这样的:
public void actionPerformed(ActionEvent e)
{
new ClassB(cfgFile).execute();
}
这篇关于如何将参数传递给SwingWorker?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文