且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在进行计算时显示进度条

更新时间:2021-09-09 21:56:55

编辑:我认为,如果您从我的回答中考虑到逻辑更改,并将其作为 John 建议,您将一切准备就绪;)

EDIT: I think if you take the changes in logic into account from my answer, and place it in a background process as John suggests, you'll be all set ;)

我认为您可能希望将完成百分比的计算移到for循环中,以便在进行迭代时更新进度.

I think you may want to move your calculation of the percentage complete into your for loop so that it will update the progress as you make your iterations.

//MAKES LOADING SCREEN
JFrame f = new JFrame("Loading...");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
Border border = BorderFactory.createTitledBorder("Calcualating...");
progressBar.setBorder(border);
content.add(progressBar, BorderLayout.NORTH);
f.setSize(300, 100);
f.setVisible(true);

double percent = 0;
int intPercent = 0;
progressBar.setValue(intPercent);
//Calculates Pi
for (i = 1.0; i <= iterations; i++)
{
    stage = stage + y/x;
    y = - y; //Flips Sign
    x+=2; 
    //CALCULATE PERCENT COMPLETE
    percent = 100*(i/iterations);
    intPercent = (int) (percent + 0.5); //Adds .5 in order to round.
    progressBar.setValue(intPercent);
    //STOP CALCULATING PERCENT COMPLETE
}

myPi = 4*stage;
System.out.println("My Pi: " + myPi);
//STOP CALCULATING PI