Ber*_*rty 1 java user-interface jprogressbar
我有一个程序需要一些时间来创建 pdf 文件我想向用户显示进度
当我完成一个 pdf 文件时,我尝试调用进度条来更新它的状态:
ProgressDialog progress = new ProgressDialog(instance, numberOfInvoices);
progress.setVisible(true);
progress.setAlwaysOnTop(true);
for(int i = 0 ; i<numOfPdfs ; i++){
progress.change(i + 1);
}
Run Code Online (Sandbox Code Playgroud)
进度对话框如下所示:
public class ProgressDialog extends JDialog {
private JProgressBar progressBar;
public ProgressDialog(Window parent, int aantal) {
super(parent);
this.setPreferredSize(new Dimension(300, 150));
progressBar = new JProgressBar(0, aantal);
progressBar.setValue(0);
progressBar.setSize(new Dimension(280, 130));
this.add(progressBar, BorderLayout.CENTER);
this.pack();
this.setLocationRelativeTo(parent);
}
public void change(int aantal) {
if (aantal < progressBar.getMaximum() && aantal >= 0) {
progressBar.setValue(aantal);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我得到的只是一个空窗口(白色)
我在这个论坛上环顾四周,但踏板解决方案似乎太复杂了
在计算 2 个 pdf 文件之间,我应该能够更新 gui,对吗?
好的科林
我试过这个:(完整课程)
public class ProgressDialog extends JDialog {
private JProgressBar progressBar;
private String message;
private static int number;
public ProgressDialog(Window parent, int max, String message) {
super(parent);
this.message = message;
this.setPreferredSize(new Dimension(300, 150));
progressBar = new JProgressBar(0, max);
progressBar.setValue(0);
progressBar.setSize(new Dimension(280, 130));
progressBar.setString(message + " 0/" + progressBar.getMaximum());
progressBar.setStringPainted(true);
this.add(progressBar, BorderLayout.CENTER);
this.pack();
this.setLocationRelativeTo(parent);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
public void change(int number) {
ProgressDialog.number = number;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
int number = ProgressDialog.getAantal();
if (number < progressBar.getMaximum() && number >= 0) {
progressBar.getModel().setValue(number);
progressBar.setString(message + " " + progressBar.getValue() + "/" + progressBar.getMaximum());
System.out.println("progressbar update: " + number + "/" + progressBar.getMaximum());
} else {
setCursor(null);
System.out.println("progressbar terminated");
}
}
});
}
public static int getAantal(){
return number;
}
}
Run Code Online (Sandbox Code Playgroud)
现在它仍然显示空窗口,但是当所有 pdf 准备就绪时,它确实显示进度条,完成 0% 然后它关闭(就像它应该做的那样)
知道为什么它在过程中保持空白吗?
你确实需要用线程来做。最好学习它而不是逃避,因为它是一种常见的 GUI 框架设计。
它可以很简单:
public void change(int aantal) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (aantal < progressBar.getMaximum() && aantal >= 0) {
progressBar.setValue(aantal);
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
或替换invokeLater()为invokeAndWait().