从另一个线程更新jProgressBar

时间:2015-05-27 14:22:23

标签: java

我是java的新手。我试图了解java中的thraeads和timers。从另一个线程中更新ProgressBar对我来说是个大问题。我阅读了很多帖子并找到了答案。所以你能说这是解决我的任务的最好方法吗?所以,我想要的是运行第二个线程,当它完成后,停止进度条并更改按钮上的文本。所以我在测试类:

中使用按钮和进度条创建框架

enter image description here

在我意识到Button的动作监听器运行第二个线程之后:

       public class Test extends javax.swing.JFrame {



              RunBg thread = new RunBg();

            .... 
    // declaration for button, progressbar and main() method
    ....

            private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      


// needed to check is the thread running at first time else creat new object and rund hread again cause thread can be executed once

                    if(thread == null){
                        thread = new RunBg();
                    }

                    if (jProgressBar1.isIndeterminate()) {
                        jProgressBar1.setIndeterminate(false);
                        jButton1.setText("Run!");
                        thread.suspend();
                    } else {

                        jButton1.setText("Working...");
                        jProgressBar1.setIndeterminate(true);

// let us know is the second thread running or nope so we can know resume it or pause
                        if (thread.isAlive()) {
                            thread.resume();
                        } else {
                            thread.start();
                        }

                        timer.start();


                    }


                } 



    /*
    Then I creat timer to know is my thread still alive else change Progress bar and button

    */

       Timer timer = new Timer(100, new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if(!thread.isAlive()){

                            thread.stop();
                            jProgressBar1.setIndeterminate(false);
                            jButton1.setText("Запустить!");
                            timer.stop();
                        //    thread.interrupt();
                            thread = null;

                        }
                    }
        });  


      ...
    // end of class
    }

我的另一个名为RunBG的线程的第二个类:

public class RunBg extends Thread{

    int i = 0;

    public void run(){

        while(i<20000){
                System.out.println(">>>"+i);
                i++;
            }
        System.out.println("<<<Finished>>>");


    }

}

Everythig工作正常,但我有疑问。有没有更好的方法来实现我的任务或者我犯了一些错误。此外,我认为我的代码将帮助其他寻求帮助的初学者了解它是如何工作的。

0 个答案:

没有答案