2013-10-22 38 views
0

當達到某個值時,我正在關閉一個jFrame窗口,即100。該框架只是一個進度條,用於演示計算的範圍。百分比= 100時如何退出?下面我有我的代碼。jFrame當達到某個值時退出

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); 
    long i = 0; 
    int x = 0; 
    int itinerations = 1; 
    int percent = 100/itinerations; 

    System.out.println("How many itinerations?"); 
    itinerations = keyboard.nextInt(); 

    for(i = 0; i <= itinerations; i++) 
    { 
    x = x + 5; //Will be replaced with more complicated stuff later 

    } 


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

System.out.println(x); 


} 
} 

回答

2

我建議你閱讀How to Use Progress Bars Swing的教程例子,因爲你當前的代碼結構將不支持您的要求。這是你不斷需要更新進度欄的值,所以你需要某種循環。

此外,我懷疑你應該使用JFrame。通常,您會在主應用程序中使用彈出的JDialog。完成任務後,請參閱Nizil關閉對話框的建議。

+0

謝謝,我認爲Swing教程使事情變得更容易! – Cdog101

1

你也許可以使用java.awt.Window#dispose()

+0

+1用於關閉窗口的最簡單方法。 – camickr

+0

雖然是一個很好的提示,但這並不能完全回答以下問題:* jFrame在達到值時退出* *** *** – dic19

-1

這裏的簡單過程:

if(progressbar.getValue==100){ 
    System.exit(0); 
} 
+0

這完全沒有回答這個問題:*** jFrame *** *當值達到時退出*。即使可能發生大量錯誤,System.exit(0)完成'JVM'執行返回'0'(它意味着成功)。這是完成程序執行的最糟糕的方式。 – dic19

+0

對不起,我以爲他想關閉程序:3 使用frame.dispose()然後:) –