0

好的,我有这个示例 Java 代码。你们中的许多人可能以前见过它。由于我对 Java 很陌生,我想知道在 ProgressBar 达到 100% 或在我的情况下是 num >= 2000 之后,您实际上是如何调用程序来关闭的?

代码:

    package progress;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ProgressMonitor extends JFrame {
JProgressBar current;
JTextArea out;
JButton find;
Thread runner;
int num = 0;

public ProgressMonitor()
{
    super("Progress monitor");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(205,68);
    setLayout(new FlowLayout());
    current = new JProgressBar(0,2000);
    current.setValue(0);
    current.setStringPainted(true);
    add(current);
}
public void iterate()
{
    while(num<2000){
    current.setValue(num);
    try{
        Thread.sleep(1000);

    }catch (InterruptedException e) { }
    num+=95;
    }
}   


    public static void main(String[] args) {
        ProgressMonitor pm = new ProgressMonitor();
        pm.setVisible(true);
        pm.iterate();

    }

}

我尝试在 while 块中使用 if 语句,所以我写了

if(num >=2000) System.exit(0);

但什么也没发生。

我还尝试转换 JProgressBar getValue() 方法并将其装箱为整数

if ((Integer)current.getValue() >= 100) System.exit(0);

和 current.getValue() >= 2000 的那个,但都不适合我。

你能帮我找到解决办法吗?先感谢您。

4

2 回答 2

0

我不太确定你的问题......但这确实有效:

public void iterate() {
    while (num < 2000) {            
        current.setValue(num);
        try {
            Thread.sleep(500);

        } catch (InterruptedException e) {
        }

        num += 95;

        if (num >= 2000)
            System.exit(0);
    }
}
于 2012-12-27T17:33:19.557 回答
0

您可以在构建 JFrame 时检查 javadoc:

public interface WindowConstants
{
    /**
     * The do-nothing default window close operation.
     */
    public static final int DO_NOTHING_ON_CLOSE = 0;

    /**
     * The hide-window default window close operation
     */
    public static final int HIDE_ON_CLOSE = 1;

    /**
     * The dispose-window default window close operation.
     * <p>
     * <b>Note</b>: When the last displayable window
     * within the Java virtual machine (VM) is disposed of, the VM may
     * terminate.  See <a href="../../java/awt/doc-files/AWTThreadIssues.html">
     * AWT Threading Issues</a> for more information.
     * @see java.awt.Window#dispose()
     * @see JInternalFrame#dispose()
     */
    public static final int DISPOSE_ON_CLOSE = 2;

    /**
     * The exit application default window close operation. Attempting
     * to set this on Windows that support this, such as
     * <code>JFrame</code>, may throw a <code>SecurityException</code> based
     * on the <code>SecurityManager</code>.
     * It is recommended you only use this in an application.
     *
     * @since 1.4
     * @see JFrame#setDefaultCloseOperation
     */
    public static final int EXIT_ON_CLOSE = 3;

}
于 2012-12-28T13:38:21.433 回答