gpt4 book ai didi

java - 计算进行时显示进度条

转载 作者:行者123 更新时间:2023-12-02 08:48:25 26 4
gpt4 key购买 nike

我正在编写代码来计算 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。

请参阅这些以获得一些指导,谷歌会找到更多。

How do you use the Event Dispatch Thread?

Java Background thread

关于java - 计算进行时显示进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19579291/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com