如何根据java中任务所花费的时间设置jProgressBar

时间:2013-10-11 07:33:06

标签: java jprogressbar

我正在开发加密解密文件的应用程序,我想根据流程的实际时间使用jProgressBar。

1 个答案:

答案 0 :(得分:2)

要根据任务所需的时间使jProgressBar工作,您应该使用SwingWorker在单独的线程中执行任务。

SwingWorker如何运作?

  

SwingWorker适用于需要在后台线程中运行长时间运行任务并在完成或处理时为UI提供更新的情况。 SwingWorker的子类必须实现doInBackground()方法才能执行后台计算。

     

工作流

     

SwingWorker的生命周期涉及三个线程:

     

当前线程:在此线程上调用execute()方法。它为工作线程上的执行调度SwingWorker并立即返回。可以使用get方法等待SwingWorker完成。

     

工作线程:此线程调用doInBackground()方法。这是所有背景活动应该发生的地方。要通知PropertyChangeListeners绑定的属性更改,请使用firePropertyChangegetPropertyChangeSupport()方法。默认情况下,有两个可用的绑定属性:状态和进度。

     

事件调度线程:此线程上发生所有与Swing相关的活动。 SwingWorker调用process和done()方法并通知此线程上的任何PropertyChangeListeners。

     

通常,Current线程是Event Dispatch Thread。

因此,要开发一个加密和解密文件的应用程序,您可以根据流程的实际时间使用SwingWorker执行加密/解密和jProgressBar。

样本输出:

enter image description here

代码:

public class Test extends JPanel implements ActionListener,
        PropertyChangeListener {

    private JProgressBar progressBar;
    private JButton startButton;
    private JTextArea encryptedOutput;
    private JTextArea decryptedOutput;
    private Task task;

    Key aesKey;
    Cipher cipher;
    String key = "Code1234Code1234"; // 128 bit key

    class Task extends SwingWorker<Void, Void> {
        @Override
        public Void doInBackground() {
            int progress = 0;
            // Initialize progress property.
            setProgress(0);

            try {

                JFileChooser fileopen = new JFileChooser();
                FileFilter filter = new FileNameExtensionFilter("txt files",
                        "txt");
                fileopen.addChoosableFileFilter(filter);

                File file = null;
                String fileName = "";
                int ret = fileopen.showDialog(null, "Open file");

                if (ret == JFileChooser.APPROVE_OPTION) {
                    file = fileopen.getSelectedFile();
                    fileName = file.getName();

                    encryptedOutput.setText(String.format(
                            "Encrypted Output :  %s\t\n\n", fileName));
                    decryptedOutput.setText(String.format(
                            "Decrypted Output  : %s\t\n\n", fileName));
                    BufferedReader in = new BufferedReader(new FileReader(file));
                    String line = in.readLine();
                    long readLength = 0;
                    long totalLength = file.length();
                    double lengthPerPercent = 100.0 / totalLength;
                    // added dummy delay because encryption takes very less time
                    // in MVCE
                    Thread.sleep(1000);
                    while (line != null) {
                        try {

                            Thread.sleep(100);
                            // encrypt the text
                            cipher.init(Cipher.ENCRYPT_MODE, aesKey);
                            byte[] encrypted = cipher.doFinal(line.getBytes());

                            encryptedOutput.append(String.format("%s\n",
                                    new String(encrypted)));

                            // decrypt the text
                            cipher.init(Cipher.DECRYPT_MODE, aesKey);
                            String decrypted = new String(
                                    cipher.doFinal(encrypted));
                            decryptedOutput.append(String.format("%s\n",
                                    decrypted));

                            // calculate progress.
                            readLength += line.length();
                            progress = (int) (lengthPerPercent * readLength);
                            setProgress(Math.min(progress, 100));
                            line = in.readLine();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        /*
         * Executed in event dispatching thread
         */
        @Override
        public void done() {
            setProgress(100);
            Toolkit.getDefaultToolkit().beep();
            startButton.setEnabled(true);

            // turn off the wait cursor
            setCursor(null);
        }
    }

    public Test() {

        super(new BorderLayout());

        // Create key and cipher
        aesKey = new SecretKeySpec(key.getBytes(), "AES");
        try {
            cipher = Cipher.getInstance("AES");
        } catch (Exception e) {
            e.printStackTrace();
        }

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

        encryptedOutput = new JTextArea(20, 50);
        encryptedOutput.setMargin(new Insets(5, 5, 5, 5));
        encryptedOutput.setEditable(false);
        encryptedOutput.setLineWrap(true);

        decryptedOutput = new JTextArea(20, 50);
        decryptedOutput.setMargin(new Insets(5, 5, 5, 5));
        decryptedOutput.setEditable(false);
        decryptedOutput.setLineWrap(true);

        startButton = new JButton("Start Encoding");
        startButton.setActionCommand("start");
        startButton.addActionListener(this);

        JPanel panel = new JPanel();
        add(panel, BorderLayout.PAGE_START);
        panel.add(progressBar, BorderLayout.LINE_START);
        add(new JScrollPane(encryptedOutput), BorderLayout.LINE_START);
        add(new JScrollPane(decryptedOutput), BorderLayout.LINE_END);
        panel.add(startButton, BorderLayout.PAGE_END);
        setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50));

    }

    public void actionPerformed(ActionEvent evt) {
        startButton.setEnabled(false);
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        task = new Task();
        task.addPropertyChangeListener(this);
        task.execute();
    }

    /**
     * Invoked when task's progress property changes.
     */
    public void propertyChange(PropertyChangeEvent evt) {
        if (evt.getPropertyName().equals("progress")) {
            int progress = (Integer) evt.getNewValue();
            progressBar.setValue(progress);
            encryptedOutput.append("\n\n");
        }
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JComponent newContentPane = new Test();
        newContentPane.setOpaque(true);
        frame.setContentPane(newContentPane);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

相关文档: