有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在ProgressBar达到100时退出应用程序?

好的,各位,我有这个示例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);

还有一个是电流。getValue()>;=2000也一样,但对我来说都不管用

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


共 (2) 个答案

  1. # 1 楼答案

    您可以在构建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;
    
    }
    
  2. # 2 楼答案

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

    public void iterate() {
        while (num < 2000) {            
            current.setValue(num);
            try {
                Thread.sleep(500);
    
            } catch (InterruptedException e) {
            }
    
            num += 95;
    
            if (num >= 2000)
                System.exit(0);
        }
    }