繁体   English   中英

当我单击进度条关闭按钮时,它应该询问确认并停止进度条后台任务

[英]When i click on the progress bar close button it should ask the confirmation and stop the progress bar background task

我在Java swing应用程序中添加了进度条。 当我单击进度条关闭按钮时,当用户选择“是”时,它应该要求确认并停止进度条后台任务,而不是终止进度条和后台任务,否则按原样启动进度条线程并执行后台任务。

谁能指导我解决这个问题?

任何意见表示赞赏。 谢谢,拉胡尔


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

我希望当我单击进度栏的关闭按钮时,它应该提示我进行确认。 当确认对话框打开时,在后台执行工作的swing worker线程应该在wait()中。 如果用户选择“是”,则应关闭进度条;如果用户选择“否”,则应启动swing worker的wait()线程,然后再次开始执行后台进程。

当前当我尝试了task.wait(); 所有这些都使主线程停止等待..... !!! 有什么建议么?

我假设您正在使用带有进度栏的计时器,因为您没有发布代码,请发布SSCCE
无论如何,在actionPerfomed方法内部,您必须具有条件语句来检查选定的选项YesNo
在停止计时器直到用户选择它之前,然后:

if(Yes):停止计时器并将进度值设置为零,并重置您在计时器的 actionListener中使用的所有变量。
if(no):启动计时器。

注意:在您尝试任何操作之前,除非您向我们展示,否则我不会发布代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM