当JProgressBar达到100%时,如何使JDialog不可见?

时间:2015-04-20 11:23:22

标签: java swing jdialog jprogressbar

相关的代码:

JProgressBar progress;
JButton button;     
JDialog dialog;      //Fields of my GUI class

progress=new JProgressBar(JProgressBar.HORIZONTAL,0,100);
button=new JButton("Done");
dialog=new JDialog();             //Done from methods

progress.setValue(0);
progress.setStringPainted(true);
progress.setBorderPainted(true);  //Also done from methods

button.addActionListener(this);   //Also done from methods

dialog.setLayout(new FlowLayout(FlowLayout.CENTER));
dialog.setTitle("Please wait...");
dialog.setBounds(475,150,250,100);
dialog.setModal(true);            //Also done from methods

dialog.add(new JLabel("Loading..."));
dialog.add(progress);             //Also done from methods

这是actionPerformed方法:

public void actionPerformed(ActionEvent e)
{
    dialog.setVisible(true);
    Task task=new Task();
    task.start();


    //After the JProgressBar reaches 100%, do the following things:
    /*progress.setValue(progress.getMinimum());
    dialog.setVisible(false);*/
}

TaskactionPerformed方法正下方的嵌套类:

private class Task extends Thread {    
  public void run(){
     for(int i =0; i<= 100; i++){
        final int j = i;
        SwingUtilities.invokeLater(new Runnable() {
           public void run() {
              progress.setValue(j);
           }
        });
        try {
           Thread.sleep(10);
        } catch (InterruptedException e) {}
     }
  }
} 

当JProgressBar达到100%时,我希望JDialog不可见。目前,当JProgressBar达到100%时,JDialog不会关闭。实际上,我想在actionPerformed中的注释代码片段在JProgressBar达到100%之后执行。

我在task.join();之后尝试了task.start();,但这会产生负面结果。当我这样做时,显示了JDialog的边框,然后片刻之后,对话框关闭。我从来没有在JDialog中看到任何东西。

请注意,我是SwingUtilities的新手。

如何使程序完成我期望的工作?

1 个答案:

答案 0 :(得分:2)

怎么样:

public void run() {
          if(j == 100)
              dialog.dispose();
          else
              progress.setValue(j);
       }