在循环中进行JProgressBar更新值的问题(线程化) [英] Problem making a JProgressBar update values in Loop (Threaded)

查看:133
本文介绍了在循环中进行JProgressBar更新值的问题(线程化)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试让我的程序在执行某些操作时不断更新方法中的进度条值。然而,直到最后才会发生这种情况,并且UI会冻结。

Am trying to get my program to update the progress bar values constantly within a method while performing some operations. However this does not happen until the end, and the UI freezes.

在查看与我的问题类似的问题之后,我尝试实现已接受的解决方案(使用线程)但是我无法使其正常工作。就像他们不在那里一样。

After looking around to similar questions with my problems, I tried to implement the accepted solutions (Using threads) however I cannot get it to work correctly. Is just like if they where not there.

我的程序包含几个类, Main 是自动创建的类通过Netbeans在JFrame Design 模式下,所以有一些东西,比如 static void main public Main 我不确定它的一些内容。在我将把这些方法的片段与我的线程实现一起。

My program contains several classes, the Main being the one automatically created by netbeans on the JFrame Design mode, so there are certain things such as the static void main and the public Main that am not really sure of some of its contents. Under i will put the snippets of those methods, together with my thread implementation.

public class Main extends javax.swing.JFrame implements ActionListener, Runnable{
                                          // I added implements ActLis, Runn.....

...

static Main _this;      // I included this variable

...

public static void main(String args[]) {
        Main m = new Main();                               // Added by me
        new Thread(m).start();                             // Added by me
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
 }

...

public Main() {
        initComponents();
        _this = this;        // Added by me
}


...

// I also included these 2 methods in the class

public void actionPerformed(ActionEvent e) {                                    
    synchronized(this){                                                         
        notifyAll();                                                            
    }                                                                           
}                                                                               

public void run() {                                                             
    try{synchronized(this){wait();}}
    catch (InterruptedException e){}
    progressBar.setValue(50);                                                   
}

...

private void buttonPressed(java.awt.event.MouseEvent evt) {
   for(int i=0; i<=100; i++) {
      for(int j=0; j<=5; j++) {
         // does some work
      }
   run();
   }
}

我评论的所有内容都是我添加了...... 根据我在网上看到的教程和答案,我推出的东西,但似乎没有任何工作,感觉我已经尝试了接近一百万种不同的组合......

All the things that I commented as I added... are things that I putted according to tutorials and answers I have seen online, but nothing seems to work and it feels like I have tried close to a million different combinations...

提前感谢您的帮助。

推荐答案

这里有一些基础让你看一下,如果你能研究它并理解为什么每一段代码都在那里,那么我认为它会有所帮助。随意在评论中提问(虽然我现在要睡觉了!)

Here's some basis for you to look at, if you can study it and understand why every piece of code is there then I think it will help. Feel free to ask questions in a comment (although I'm going to bed right now!)

示例:

public class ProgressBarDemo extends JFrame {
    private final JProgressBar progressBar = new JProgressBar(0, 100);
    private int progressCounter = 0;

    public ProgressBarDemo() {
        setContentPane(progressBar);
        setPreferredSize(new Dimension(100, 100));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        new Thread(new Runnable() {
            public void run() {
                while (progressCounter <= 100) {
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            progressBar.setValue(progressCounter++);
                        }
                    });
                    try { Thread.sleep(500); } catch (InterruptedException e) {}
                }
            }
        }).start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ProgressBarDemo().setVisible(true);
            }
        });
    }
}

使用SwingWorker来解决问题的两种不同方法:

Two different ways to approach the problem, using SwingWorker instead:

SwingWorker示例1:

    ....
    public ProgressBarDemo() {
        setContentPane(progressBar);
        setPreferredSize(new Dimension(100, 100));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();

        SwingWorker<Integer, Void> worker = new SwingWorker<Integer,Void>() {
            public Integer doInBackground() {
                while (progressCounter <= 100) {
                    setProgress(progressCounter++);
                    try { Thread.sleep(500); } catch (InterruptedException e) {}
                }
                return 0;
            }
        };
        worker.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent event) {
                if ("progress".equals(event.getPropertyName())) {
                    progressBar.setValue((Integer)event.getNewValue());
                }
            }
        });
        worker.execute();
    }
    ....

SwingWorker示例2(不是很好,但有趣的是):

    ....
    public ProgressBarDemo() {
        setContentPane(progressBar);
        setPreferredSize(new Dimension(100, 100));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();

        new SwingWorker<Integer,Integer>() {
            public Integer doInBackground() { 
                while (progressCounter <= 100) {
                    publish(progressCounter++);
                    try { Thread.sleep(500); } catch (InterruptedException e) {}                    
                }
                return 0;
            }
            public void process(List<Integer> progresses) {
                Integer maxProgress = null;
                for (int progress : progresses) {
                    if (maxProgress == null || progress > maxProgress) {
                        maxProgress = progress;
                    }
                }
                progressBar.setValue(maxProgress);
            }
        }.execute();
    }
    ....

这篇关于在循环中进行JProgressBar更新值的问题(线程化)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆