Domanda

I re-design my code for this job. Last situation of app like below;

GUI class;

GUI Screen

Second Class: 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;

    }

}

I have buton action in GUI;

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

When program launched, GUI screen come to screen and user select two dates and press GO buton.

When i press the button Swingworker succesfully get user selected values from GUI screen and print result to screen. Just i want add progress monitor to this project.

Just i want When GO button clicked on GUI a progress monitor shoudl appear on screen and show the worker status. But i dont know how implement totally new progressmonitor frame to this project and say listen the worker.

Thanks.

È stato utile?

Soluzione

This is similar to your previous question. I recommended you to use SwingWorker and you did it that is nice!.

But you don't pay attention to this. I use Property Change Listeners. In the code i use in anonymous class. When you call in swingWorker setProgress as progress it's a bound property then when you change that value with setProgress its notifies all it's listeners!

I made a simple example for you.

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;
        }
    }

}

EDIT

As you said in comments you need to show in another frame, i recommend to show you in a dialog, you can use a Progress Monitor here you have a complete example.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top