简体   繁体   English

在进行长时间比较时更新JProgressBar

[英]Updating a JProgressBar while doing a long comparison

I got a serious problem with my recent project: I am doing a long comparison in a methode called writer(...) and it takes about 20 seconds. 我最近的项目遇到了一个严重的问题:我在一个名为writer(...)的方法中进行了长时间的比较,大约需要20秒。 The methode is decalred in the View class, where my GUI elements are setted also. 方法在View类中被decalred,我的GUI元素也被设置在其中。 While the method is comparing, I would like to update a progressbar, but anyway I do it, it's always getting updated when the methode has done it's comparison... Any ideas? 虽然这个方法正在比较,但我想更新一个进度条,但无论如何我都这样做了,当方法完成它的比较时,它总会得到更新......有什么想法吗?

Here's my code (okay - parts of it): 这是我的代码(好吧 - 部分内容):

    Thread t = new Thread(new Runnable()
{
    public void run()
    {
        writer(List1, List2);
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {

                bar.setValue(SOME_VALUE);
            }
        });
    }
});

The thread ist started through an ActionListener of an button with 线程是通过一个按钮的ActionListener启动的

t.start();

Your code as it is right now, invokes the invokeLater only after the writer has returned. 你的,因为它的代码是现在,调用invokeLater唯一的后writer又回来了。 This is because the invokeLater is in the same thread as the actual work, so both statements will be executed sequentially. 这是因为invokeLater与实际工作位于同一个线程中,因此两个语句将按顺序执行。 What you need to do is to schedule progress bar updates from within the writer . 什么,你需要做的是从内安排进度条更新writer If you don't want to clutter the writer with interface-updating logic, consider using Observer pattern. 如果你不希望扰乱了writer与接口更新逻辑,可以考虑使用Observer模式。

It gets updated in the end because that's where you update it. 它最终会更新,因为这是您更新它的地方。 You need to do the bar.setValue() (in EDT, like you already correctly do), every time you need to update the bar. 每次需要更新栏时,你需要执行bar.setValue() (在EDT中,就像你已经正确做的那样)。

A cleaner approach, perhaps, is using a SwingWorker . 或许,更简洁的方法是使用SwingWorker Use publish() when the value has updated. 值更新后使用publish() SwingWorkers can coalesce multiple changes to one, and you can ignore all but the last one (like you likely want to do in your case) in process() . SwingWorkers可以将多个更改合并为一个,并且您可以在process()忽略除最后一个之外的所有更改(就像您可能希望在您的情况下那样做process()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM