How View ProgressMonitor Progress In Real Time?

丶灬走出姿态 提交于 2020-01-25 08:56:06

问题


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

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.


回答1:


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).

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.

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


来源:https://stackoverflow.com/questions/58020090/how-view-progressmonitor-progress-in-real-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!