【问题标题】:How can I pass arguments into SwingWorker?如何将参数传递给 SwingWorker?
【发布时间】:2011-12-15 06:38:11
【问题描述】:

我正在尝试在我的 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) 
        {
        }
    }
}

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

【问题讨论】:

    标签: java swing argument-passing swingworker


    【解决方案1】:

    为什么不给它一个 File 字段并通过一个接受 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. ***
            }
        }
    }
    

    然后像这样运行它:

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

    【讨论】:

    • 既然 File 是构造函数的输入(不是执行方法),不应该这样运行吗?新 ClassB(cfgFile).execute();
    • @james.garriss:确实应该。错误已更正,谢谢!
    • 我可能需要一个通用的 SwingWorker 类!
    【解决方案2】:

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

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

    }

    【讨论】:

    • 我不是用户,这个变体对@Hovercraft 之前的answer 增加了任何内容。
    • 对不起。这两个答案之间的时间间隔非常短。当我在不知情的情况下准备答案时提交了第一个答案。
    猜你喜欢
    • 1970-01-01
    • 2020-10-09
    • 2012-12-21
    • 2012-01-07
    • 2014-05-03
    • 2015-06-26
    • 2012-01-18
    • 2017-07-14
    • 2018-03-08
    相关资源
    最近更新 更多