0

I have added a progress bar in my java swing application. When i click on the progress bar close button it should ask for confirmation and stop the progress bar background task when the user select yes than terminate the progress bar and background task otherwise start the progress bar thread as it is and do the background task.

Can anyone guide me for this issue?

Any comments are appreciated. Thanks, Rahul


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.util.Random;

public class ProgressBarDemo extends JPanel implements ActionListener,
        PropertyChangeListener, Runnable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private JProgressBar progressBar;
    private JButton startButton;
    private JTextArea taskOutput;
    private Task task=new Task();;

    // private final Object lock = new Object();

    class Task extends SwingWorker<Void, Void> implements Runnable {
        /*
         * Main task. Executed in background thread.
         */

        @Override
        public Void doInBackground() {
            Random random = new Random();
            int progress = 0;
            // Initialize progress property.
            setProgress(0);
            while (progress < 100) {
                // Sleep for up to one second.
                try {
                    Thread.sleep(random.nextInt(1000));
                } catch (InterruptedException ignore) {
                }
                // Make random progress.
                progress += random.nextInt(10);
                setProgress(Math.min(progress, 100));
            }
            return null;
        }

        /*
         * Executed in event dispatching thread
         */
        @Override
        public void done() {
            Toolkit.getDefaultToolkit().beep();
            startButton.setEnabled(true);
            setCursor(null); // turn off the wait cursor
            taskOutput.append("Done!\n");
        }
    }

    @Override
    public void run() {

    }

    public ProgressBarDemo() {
        super(new BorderLayout());

        // Create the demo's UI.
        startButton = new JButton("Start");
        startButton.setActionCommand("start");
        startButton.addActionListener(this);

        progressBar = new JProgressBar(0, 100);
        progressBar.setValue(0);
        progressBar.setStringPainted(true);

        taskOutput = new JTextArea(5, 20);
        taskOutput.setMargin(new Insets(5, 5, 5, 5));
        taskOutput.setEditable(false);

        JPanel panel = new JPanel();
        panel.add(startButton);
        panel.add(progressBar);

        add(panel, BorderLayout.PAGE_START);
        add(new JScrollPane(taskOutput), BorderLayout.CENTER);
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    }

    /**
     * Invoked when the user presses the start button.
     */
    public void actionPerformed(ActionEvent evt) {
        startButton.setEnabled(false);
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        // Instances of javax.swing.SwingWorker are not reusuable, so
        // we create new instances as needed.
        //task = new Task();
        task.addPropertyChangeListener(this);
        task.execute();
    }

    /**
     * Invoked when task's progress property changes.
     */
    public void propertyChange(PropertyChangeEvent evt) {

        if ("progress" == evt.getPropertyName()) {
            int progress = (Integer) evt.getNewValue();
            progressBar.setValue(progress);
            taskOutput.append(String.format("Completed %d%% of task.\n",
                    task.getProgress()));
        }
    }

    /**
     * Create the GUI and show it. As with all GUI code, this must run on the
     * event-dispatching thread.
     */
    private void createAndShowGUI() {
        // Create and set up the window.
        JFrame frame = new JFrame("ProgressBarDemo");
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

        // Create and set up the content pane.
        JComponent newContentPane = new ProgressBarDemo();
        newContentPane.setOpaque(true); // content panes must be opaque
        frame.setContentPane(newContentPane);
        // Display the window.
        frame.pack();
        frame.setVisible(true);
        frame.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent we) {
                String ObjButtons[] = { "Yes", "No" };

                try {
                    synchronized (task) {
                        System.out.println(task.getState());
                        task.wait();
                        System.out.println(task.getState());

                    }
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                int PromptResult = JOptionPane.showOptionDialog(null,
                        "Are you sure you want to exit?",
                        "Confirmation...!!!",
                        JOptionPane.DEFAULT_OPTION,
                        JOptionPane.WARNING_MESSAGE, null, ObjButtons,
                        ObjButtons[1]);

                if (PromptResult == 0) {
                    System.exit(0);

                } else {
                    synchronized (task) {
                        task.notify();
                    }
                }
            }
        });
    }

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

I wants that when i click on the close button of the progress bar it should prompt me for confirmation . When the confirmation dialog opens the swing worker thread which is doing work in background should be in wait(). when user selects the yes than it should close the progress bar or if user selects the no button than start the wait() thread of swing worker and start the execution of the background process again.

Currently when i have tried task.wait(); it all stops the main thread to wait.....!!! Any suggestions?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Rahul Singh
  • 19
  • 1
  • 6

1 Answers1

1

I assume that you are using timer with progressbar as you didn't post your code, please post SSCCE.
Anyway, inside actionPerfomed method you must have a condition statement checking the selected option either Yes or No:
Before anything stop the timer till the user chooses it's choice, then:

if(Yes) : stop the timer and set the progress's value to Zero and reset all the variables you used inside the timer's actionListener.
if(no): start the timer.

NOTE: I will not post the code until you show us if you tried anything.

Azad
  • 5,047
  • 20
  • 38