我正在编写代码来计算 Pi 的值,有时可能需要很长时间才能计算。我添加了一个进度条来显示进度,但代码完全按照我的指示执行,它在计算后打开进度条,然后立即关闭它(当值达到 100 时它会关闭。)
我试图将进度条的代码粘贴到循环中,但很快我意识到这解决了解决方案,但创建了多个进度条窗口。
如果放在计算之前,进度条保持为0(显然)
我在下面显示了我的代码:
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.border.Border;
import java.util.Scanner;
public class PicCalc
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
double i = 0;
double stage = 1;
int iterations = 1;
int x = 3; //Simply a variable to calculate pi
double y = -1.0; // Another variable for pi
double myPi; //This is my calculation of Pi, don't eat it.
System.out.println("Hello! I calculate Pi and compare it to the acutal value of Pi!");
System.out.println("How many iterations?");
iterations = keyboard.nextInt();
//Calculates Pi
for (i = 1.0; i <= iterations; i++)
{
stage = stage + y/x;
y = - y; //Flips Sign
x+=2;
}
myPi = 4*stage;
System.out.println("My Pi: " + myPi);
//STOP CALCULATING PI
//CALCULATE PERCENT COMPLETE
double percent = 100*(i/iterations);
int intPercent = (int) (percent + 0.5); //Adds .5 in order to round.
//STOP CALCULATING PERCENT COMPLETE
//MAKES LOADING SCREEN
JFrame f = new JFrame("Loading...");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
JProgressBar progressBar = new JProgressBar();
progressBar.setValue(intPercent);
progressBar.setStringPainted(true);
Border border = BorderFactory.createTitledBorder("Calcualating...");
progressBar.setBorder(border);
content.add(progressBar, BorderLayout.NORTH);
f.setSize(300, 100);
f.setVisible(true);
//END OF MAKING LOADING SCREEN
//CLOSES LOADING SCREEN WHEN 100% IS ACHIEVED
if (percent >= 100)
{
f.dispose();
}
//END OF CLOSING SCREEN HERE
你只有一个线程,所以 GUI 永远没有机会更新(因为它正忙于计算)。
正常的方法是将计算放在后台线程中,以便事件调度线程 (EDT) [又名 GUI 线程] 可以自由地更新 GUI。
请参阅这些以获得一些指导,谷歌会发现更多。
如何使用事件调度线程? https://stackoverflow.com/questions/7896723/how-do-you-use-the-event-dispatch-thread
Java后台线程 https://stackoverflow.com/questions/15026996/java-background-thread
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)