How to make the JDialog invisible when the JProgre

2019-07-23 18:28发布

Relevant piece of code:

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

And here is the actionPerformed method:

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);*/
}

Task is a nested class just below the actionPerformed method:

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

I want the JDialog not to be visible when the JProgressBar in it reaches 100% . Currently, the JDialog does not close when the JProgressBar reaches 100%. Actually, I want to the commented piece of code in actionPerformed to be executed after the JProgressBar reaches 100%.

I've tried task.join(); just after task.start();, but this gave a negative result. When I did this, the JDialog's border was displayed and then, after a moment, the dialog closes. I never see anything in the JDialog.

Note that I am new to SwingUtilities.

How do I make the program do what I am expecting?

1条回答
爷、活的狠高调
2楼-- · 2019-07-23 19:04

How about:

public void run() {
          if(j == 100)
              dialog.dispose();
          else
              progress.setValue(j);
       }
查看更多
登录 后发表回答