-2

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.

Lacrymae
  • 157
  • 1
  • 17
  • Problem Solved: I carry Swingworker class and progressbar class to my Main GUI class. So i dont need use costructor anymore and everythings working normal now. Problem was: When SwingWorker class created out of main GUI class we must use constructor. – Lacrymae Feb 18 '14 at 20:56

1 Answers1

1

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.

Community
  • 1
  • 1
nachokk
  • 14,363
  • 4
  • 24
  • 53
  • i edit my code again you can check in below. But when i click to buton worker not executed and progressbar not coming this time. I suspect progressbar not fired anywhere. Am i wrong ? – Lacrymae Feb 17 '14 at 19:42
  • @Lacrymae it's not the way stackoverflow works, you should edit your question, this part is for answers not for questions, remove that answer you made and edit your question! I can't understand what is your problem if you don't make a good(readable) question. – nachokk Feb 17 '14 at 19:47
  • Oh ok i understand i delete answer and edit my question now just a second. Edit: Ok i deleted my answer and edit my question above. You can chck last situation of my project and its problem. – Lacrymae Feb 17 '14 at 19:49
  • @Lacrymae i don't understand your custom ProgressBar it's not necessary at all. you should provide code from GUI class i recommend you to use `JProgressBar` directly! – nachokk Feb 17 '14 at 19:56
  • Hmm you offer create new Jprogressbar in main GUI right ? – Lacrymae Feb 17 '14 at 19:58
  • @Lacrymae i edited and put an example – nachokk Feb 17 '14 at 20:28
  • Thank you very much for it. I can check it and inform you. – Lacrymae Feb 17 '14 at 20:38
  • I understand the logic i think. But in this example, Main GUI, progress bar and buton integrated. Actually my GUI must be standalone app window has a action buton. When buton pressed my other swingworker must be executed and totally new progress monitor frame must be coming to screen same time. Is my request different scenario than your example right ? – Lacrymae Feb 17 '14 at 20:57
  • Problem Solved: I carry Swingworker class and progressbar class to my Main GUI class. So i dont need use costructor anymore and everythings working normal now. Problem was: When SwingWorker class created out of main GUI class we must use constructor. – Lacrymae Feb 18 '14 at 20:56