相关的代码:如何在JProgressBar达到100%时使JDialog不可见?
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);*/
}
Task
是一个嵌套类略低于actionPerformed
方法:
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) {}
}
}
}
我想的JDialog在JProgressBar达到100%时不可见。目前,当JProgressBar达到100%时,JDialog不会关闭。实际上,我想要在JProgressBar达到100%后执行actionPerformed
中的注释片段。
我试过task.join();
只是在task.start();
之后,但是这给了一个负面结果。当我这样做时,显示了JDialog的边框,然后过了一会儿,对话框关闭。我从来没有在JDialog中看到任何东西。
请注意,我是SwingUtilities
的新手。
如何让程序执行我期望的功能?
使用'SwingWorker' ......好吧,但一旦'run'方法到达终点,你需要将'dialog'一个参考,所以你可以调用'处置'对此... – MadProgrammer
@MadProgrammer,谢谢。 “对话框”在“任务”中可见。所以我可以直接使用它。但是有一个小问题。查看@ Kuba的回答下的评论 –
仅仅因为对话框是可见的,并不意味着你可以与它交互,你仍然需要对它进行某种引用。至于你“其他”的问题,请考虑使用SwingWorker代替 – MadProgrammer