Java 当JProgressBar达到100%时,如何使JDialog不可见?
相关代码:Java 当JProgressBar达到100%时,如何使JDialog不可见?,java,swing,jdialog,jprogressbar,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.set
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
下面是执行的操作
方法:
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);*/
}
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) {}
}
}
}
Task
是一个嵌套类,位于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);*/
}
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) {}
}
}
}
私有类任务扩展线程{
公开募捐{
对于(inti=0;i
public void run() {
if(j == 100)
dialog.dispose();
else
progress.setValue(j);
}
使用SwingWorker
…好的,但是一旦run
方法结束,您将需要一个对对话框的引用,这样您就可以调用dispose
。@MadProgrammer,谢谢。对话框
在任务
中可见。因此我可以直接使用它。但是有一个小问题。请参阅下面的注释@Kuba的回答仅仅因为对话框是可见的,并不意味着你可以与之互动,你仍然需要某种形式的引用。至于你“其他”问题,考虑使用摇摆工instead@MadProgrammer,谢谢。我终于用SwingWorker(SwingWorker)成功了!谢谢!但有一个小问题。当我按下JButton时,JProgressBar不会移动。它保持在0%。这种情况有时只会发生。一旦不发生,那么这个问题就不会出现。一个你知道这是什么原因吗?