如何实时查看 ProgressMonitor 进度? [英] How View ProgressMonitor Progress In Real Time?

查看:25
本文介绍了如何实时查看 ProgressMonitor 进度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    int jTableRows = jTable1.getRowCount();
    ProgressMonitor progressMonitor;
    progressMonitor = new ProgressMonitor(ImportDataFromExcel.this, "Running a Long Task", "", 0, jTableRows);
    for (int i = 0; i < jTableRows; i++) {
        String message = String.format("Completed %d.\n", i);
        progressMonitor.setNote(message);
        progressMonitor.setProgress(i);
    }
}

当我单击按钮将数据插入数据库时​​,我希望获得 ProgressMonitor 进度,但只有在整个过程完成后才能获得进度结果.如何实时查看进度.

When i click a button to insert the data in the database am expecting to get ProgressMonitor progress but am only getting the progress result when the whole process finishes. How can i view the progress in real time.

推荐答案

Swing 中所有繁重的任务都应该由 SwingWorkers.否则,事件调度线程 因此无法发生事件(GUI 将冻结).

All heavy tasks in Swing should be executed by SwingWorkers. Otherwise, the big task will give hard time to the Event Dispatch Thread hence events cannot take place (GUI will freeze).

因此,您必须创建一个 SwingWorker 并以百分比计算任务的已完成步骤并将值提供给进度条.但是,您必须记住,由于 progressbar.setValue(int value) 是一个组件更新,它应该只发生在 EDT 内部.这就是为什么你必须使用 worker 的 publishprocess 方法.

So, you have to create a SwingWorker and calculate the completed steps of the task in percentage and give the value to the progress bar. However, you have to have in mind that since progressbar.setValue(int value) is a component update, it should only happen inside EDT. That's why you have to use publish and process methods of the worker.

让我们看一个示例,我们必须在 Desktop 中将 1000 行写入文本文件并查看其进度.这是一个大任务"(我让线程休眠),所以它符合我们的情况.

Let's see an example where we have to write 1000 lines to a text file in Desktop and see its progress. This is a "big task" (I sleep the thread), so it matches our case.

public class ProgressExample extends JFrame {
    private static final long serialVersionUID = 5326278833296436018L;

    public ProgressExample() {
        super("test");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(new ProgressPanel());

        pack();
        setLocationRelativeTo(null);

    }

    private static class WriteTextWorker extends SwingWorker<Void, Integer> {
        private ProgressableView view;

        public WriteTextWorker(ProgressableView view) {
            this.view = view;
        }

        @Override
        protected void process(List<Integer> chunks) {
            int progress = chunks.get(0);
            view.setProgress(progress);
        }

        @Override
        protected Void doInBackground() throws Exception {
            publish(0);
            File desktop = new File(System.getProperty("user.home"), "Desktop");
            File textFile = new File(desktop, "stackoverflow.txt");
            int linesToWrite = 1000;
            try (FileWriter fw = new FileWriter(textFile, true);
                    BufferedWriter bw = new BufferedWriter(fw);
                    PrintWriter out = new PrintWriter(bw)) {
                for (int i = 0; i < linesToWrite; i++) {
                    out.println("This is line: " + i);
                    out.flush();
                    //Calculate percentage of completed task
                    int percentage = ((i * 100) / linesToWrite);
                    System.out.println("Percentage: " + percentage);
                    publish(percentage);
                    Thread.sleep(10); //Heavy task
                }
            }
            return null;
        }

    }

    private static class ProgressPanel extends JPanel implements ProgressableView {
        private JProgressBar progressBar;
        private SwingWorker<Void, Integer> worker;

        public ProgressPanel() {
            super(new BorderLayout());
            progressBar = new JProgressBar();
            add(progressBar, BorderLayout.PAGE_START);

            JButton writeLinesButton = new JButton("Press me to do a long task");
            writeLinesButton.addActionListener(e -> worker.execute());
            add(writeLinesButton, BorderLayout.PAGE_END);

            worker = new WriteTextWorker(this);
        }

        @Override
        public int getProgress() {
            return progressBar.getValue();
        }

        @Override
        public void setProgress(int progress) {
            progressBar.setValue(progress);
        }

    }

    public static interface ProgressableView {
        int getProgress();

        void setProgress(int progress);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new ProgressExample().setVisible(true));
    }
}

这篇关于如何实时查看 ProgressMonitor 进度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆