将进度条添加到Swing项目

时间:2014-02-16 15:43:50

标签: java swing constructor progress-bar swingworker

我为这份工作重新设计了我的代码。 app的最后情况如下;

GUI类;

GUI Screen

第二课:MySwingWorker

package exampleproject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingWorker;

public class MySwingWorker extends SwingWorker<Void, Void> {

        private GUI myGui; //Reach GUI variables.

        public MySwingWorker(GUI myGui) {
        this.myGui = myGui; 
        }

        private MySwingWorker swing;

        public MySwingWorker() {
        this.swing = swing;
        }


        //get start date from GUI and convert it wanted format.
        public String getStartDate (){
        String inputStringDate = myGui.StartDateComboBox.getText();
        SimpleDateFormat inputFormat = new SimpleDateFormat("dd.MM.yyyy");
        Date inputDate = null;
        try {
            inputDate = inputFormat.parse(inputStringDate);
        } 
        catch (ParseException ex) {
            Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00.000");
        String outputStringDate = outputFormat.format(inputDate);
        return outputStringDate;
        }

        //get end date from GUI and convert it wanted format.
        public String getEndDate (){
        String inputStringDate = myGui.EndDateComboBox.getText();
        SimpleDateFormat inputFormat = new SimpleDateFormat("dd.MM.yyyy");
        Date inputDate = null;
        try {
            inputDate = inputFormat.parse(inputStringDate);
        } 
        catch (ParseException ex) {
            Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd 23:59:59.999");
        String outputStringDate = outputFormat.format(inputDate);
        return outputStringDate;
        }

    @Override
    protected Void doInBackground() throws Exception {
        int i = 0;
        setProgress(i);

        String test1 = "Starting Date: '"+getStartDate()+"'"; //LongTask 1
        System.out.println(test1);
        while(i < 50){
             setProgress(i++);
             Thread.sleep(5); // random magic number
        }


        String test2 = "Ending Date: '"+getEndDate()+"'"; //LongTask 2
        System.out.println(test2);
        while(i < 100){
             setProgress(i++);
             Thread.sleep(5); // random magic number
        }

     return null;

    }

}

我在GUI中有按钮操作;

private void GoButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
  // TODO add your handling code here:
  MySwingWorker task = new MySwingWorker(GUI.this);
  task.execute();   
} 

当程序启动时,GUI屏幕进入屏幕,用户选择两个日期并按GO按钮。

当我按下按钮时,Swingworker成功地从GUI屏幕获取用户选择的值并将结果打印到屏幕。我想在此项目中添加进度监视器。

我只想要在GUI上点击GO按钮时,屏幕上会出现一个进度监视器并显示工作人员状态。但是我不知道如何在这个项目中实现全新的进展监控框架并且说听工人。

感谢。

1 个答案:

答案 0 :(得分:1)

这与之前的question类似。我建议你使用SwingWorker,你做的很好!。

但你不注意这一点。我使用Property Change Listeners。在我使用匿名类的代码中。 当您在swingWorker setProgress中调用progress时,它是一个绑定属性,那么当您使用setProgress更改该值时,它会通知所有听众!

我为你做了一个简单的例子。

public class GUI {

    private JPanel panel;
    private JProgressBar progressBar;
    private JButton button;

    public GUI(){
        panel = new JPanel();
        progressBar = new JProgressBar();
        button = new JButton("Press me");
        button.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                SwingWorker worker = new MySwingWorker();
                worker.addPropertyChangeListener(new PropertyChangeListener() {
                @Override
                public void propertyChange(final PropertyChangeEvent event) {
                    switch (event.getPropertyName()) {
                        case "progress":
                            progressBar.setIndeterminate(false);
                            progressBar.setValue((Integer) event.getNewValue());
                            break;
                    }
                }
            });
            //then to get start you have to use execute()
            worker.execute();
            }

        });        
        panel.add(progressBar);
        panel.add(button);


    }


    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI("SwingWorker Example");
            }
        });
    }

    private static void createAndShowGUI(String str) {            
        JFrame frame = new JFrame(str);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.add(new GUI().panel);
        frame.pack();
        frame.setVisible(true);
    }  


    static class MySwingWorker extends SwingWorker<Void,Void>{
        @Override
        protected Void doInBackground() throws Exception{
            //here you make heavy task this is running in another thread not in EDT
           int i = 0;
           setProgress(i);
           // call query 1
           while(i < 50){
             setProgress(i++);
             Thread.sleep(5); // random magic number
           }
           // then call query 2
           while(i <= 100){
             setProgress(i++);
             Thread.sleep(5); // random magic number
           }

           return null;
        }
    }

}

修改

正如您在评论中所说,您需要在另一个框架中显示,我建议您在对话框中显示,您可以使用Progress Monitor,这里有一个完整的example