如何设置运行应用程序的JProgressbar

时间:2015-03-21 17:56:14

标签: java swing

我的应用程序运行大约7秒钟。

我想做一个进步条,但我不知道如何。

你能帮帮我吗?

3 个答案:

答案 0 :(得分:2)

您应该将进度条用作不确定模式 你可以使用这样的东西:

private void dialogWaiting()
    {
        JProgressBar progressBar = new JProgressBar();
        progressBar.setIndeterminate(true);
        JTextArea msgLabel;
        final JDialog dialogWaiting;
        JPanel panel;

        msgLabel = new JTextArea("Please wait...");
        msgLabel.setEditable(false);


        panel = new JPanel(new BorderLayout(5, 5));
        panel.add(msgLabel, BorderLayout.PAGE_START);
        panel.add(progressBar, BorderLayout.CENTER);
        panel.setBorder(BorderFactory.createEmptyBorder(11, 11, 11, 11));

        dialogWaiting = new JDialog(Frame.getFrames()[0], "Doing whatever", true);
        dialogWaiting.getContentPane().add(panel);
        dialogWaiting.setResizable(false);
        dialogWaiting.pack();
        dialogWaiting.setSize(300, dialogWaiting.getHeight());
        dialogWaiting.setLocationRelativeTo(null);
        dialogWaiting.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        dialogWaiting.setAlwaysOnTop(true);     
        msgLabel.setBackground(panel.getBackground());

        SwingWorker worker = new SwingWorker() {

            @Override
            protected void done() {
                // Close the dialog
                dialogWaiting.dispose();
            }

            @Override
            protected Void doInBackground() {
                // Do the long running task here
                // put all the code you want to run as the dialogWaiting is on

                return null;
            }
        };

        worker.execute();
        dialogWaiting.setVisible(true);
    }

答案 1 :(得分:1)

基本上它就是这么简单,假设应用程序有5个方法一个接一个地执行。每个方法完成后,您可以将栏的进度设置为+ 20%。

public class App {
    public void method_1(){
        // method code
        progressbar.setValue(20);
    }
     public void method_2(){
        // method code
        progressbar.setValue(40);
    }
    public void method_3(){
        // method code
        progressbar.setValue(60);
    }
    // etc

可能是在特定的Thread期间或者线程完成时,您甚至可以将其重置为0并在新线程启动时重新开始。这一切都取决于你。

答案 2 :(得分:0)

一种方法(这有点愚蠢)是在代码中不同时间使用setValue()方法。例如:

void main(String[]args){
//assuming that you have imported the progressbar class and have instantiated it
//with the variable name "jp"
System.out.println();//simulating some work...
jp.setValue(10);
System.out.println()//simulating some work...
jp.setValue(20);
//you get the idea...