我有来自 UI 的服务器调用。它的响应时间有点高。所以我想在从服务器加载数据期间显示一个进度条。我已经使用这种方法尝试了以下代码来显示进度条。有些地方我做错了,当我calculateResult()
在按钮单击时调用该方法时,我没有看到进度条。我不需要在进度条上显示任何百分比。它只需要显示数据正在加载。
// 下面的代码我试过了。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class MyProgressBarTest extends JFrame {
private static final long serialVersionUID = 1L;
private static JProgressBar progressBar;
public static void main(String[] args) {
MyProgressBarTest obj = new MyProgressBarTest();
obj.createGUI();
}
public void createGUI() {
JPanel panel = new JPanel();
JButton button = new JButton("Progress");
progressBar = new JProgressBar();
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
MyCustomProgressBarDialog progressBarObj = new MyCustomProgressBarDialog(progressBar);
progressBarObj.createProgressUI();
MyActionPerformer actionObj = new MyActionPerformer(progressBar);
actionObj.execute();
progressBarObj.setVisible(false);
}
});
// panel.add(progressBar);
panel.add(button);
add(panel);
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setLocationRelativeTo(null);
// pack();
setSize(200, 300);
setVisible(true);
}
}
class MyActionPerformer extends SwingWorker<String, Object> {
JProgressBar fProgressBar;
public MyActionPerformer(JProgressBar progressBar) {
this.fProgressBar = progressBar;
this.fProgressBar.setVisible(true);
this.fProgressBar.setIndeterminate(true);
}
protected String doInBackground() throws Exception {
calculateResult();
return "Finished";
}
protected void done() {
fProgressBar.setVisible(false);
}
public void calculateResult() {
for (int i = 0; i < 500000; i++) {
System.out.println("Progress Bar: " + i);
}
}
}
class MyCustomProgressBarDialog extends JDialog {
private static JProgressBar progressBar;
public MyCustomProgressBarDialog(JProgressBar progressBar) {
this.progressBar = progressBar;
}
public void createProgressUI() {
add(progressBar);
setLocationRelativeTo(null);
setSize(50, 20);
setVisible(true);
}
}