简体   繁体   English

Java SwingWorker与JDialog在JDBC网络操作期间显示JProgressBar

[英]Java SwingWorker with JDialog showing JProgressBar during JDBC network operation

I have a frame which has a button, when it is pressed a JDialog with a progress bar is shown and some data is being fetched using jdbc driver (progress bar is being updated). 我有一个带有按钮的框架,当按下它时,将显示带有进度条的JDialog ,并且正在使用jdbc驱动程序获取某些数据(正在更新进度条)。 I needed a cancel button, so I spent some time figuring out how to connect everything. 我需要一个取消按钮,所以我花了一些时间弄清楚如何连接所有内容。 It seems to be working, but I sincerely am not sure if this way is any good. 它似乎正在工作,但是我衷心不确定这种方式是否有效。 If someone has some spare time please check this code and tell me if anything is wrong with it - mainly with the whole SwingWorker and cancellation stuff. 如果有人有空余时间,请检查此代码,并告诉我它是否有问题-主要是整个SwingWorker和取消操作。

On my pc (linux) the unsuccessful network connection attempt (someNetworkDataFetching method) takes a whole minute to timeout, do I have to worry about the SwingWorkers which are still working (waiting to connect despite being cancelled) when I try to create new ones? 在我的PC(Linux)上,不成功的网络连接尝试(someNetworkDataFetching方法)需要一整分钟的超时时间,当我尝试创建新的SwingWorkers时,我是否还要担心SwingWorkers仍在工作(尽管被取消,但仍在连接)?

Note: you need mysql jdbc driver library to run this code. 注意:您需要mysql jdbc驱动程序库来运行此代码。

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;

public class Test extends JFrame {

    private JProgressBar progressBar = new JProgressBar();
    private JLabel label = new JLabel();
    private DataFetcherProgress dfp;

    /**
     * This class holds retrieved data.
     */
    class ImportantData {

        ArrayList<String> chunks = new ArrayList<>();

        void addChunk(String chunk) {
            // Add this data 
            chunks.add(chunk);
        }
    }

    /**
     * This is the JDialog which shows data retrieval progress.
     */
    class DataFetcherProgress extends JDialog {

        JButton cancelButton = new JButton("Cancel");
        DataFetcher df;

        /**
         * Sets up data fetcher dialog.
         */
        public DataFetcherProgress(Test owner) {
            super(owner, true);
            getContentPane().add(progressBar, BorderLayout.CENTER);
            // This button  cancels the data fetching worker.
            cancelButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    df.cancel(true);

                }
            });
            getContentPane().add(cancelButton, BorderLayout.EAST);
            setLocationRelativeTo(owner);
            setSize(200, 50);
            df = new DataFetcher(this);
        }

        /**
         * This executes data fetching worker.
         */
        public void fetchData() {
            df.execute();
        }
    }

    class DataFetcher extends SwingWorker<ImportantData, Integer> {

        DataFetcherProgress progressDialog;

        public DataFetcher(DataFetcherProgress progressDialog) {
            this.progressDialog = progressDialog;
        }

        /**
         * Update the progress bar.
         */
        @Override
        protected void process(List<Integer> chunks) {
            if (chunks.size() > 0) {
                int step = chunks.get(chunks.size() - 1);
                progressBar.setValue(step);
            }
        }

        /**
         * Called when worker finishes (or is cancelled).
         */
        @Override
        protected void done() {
            System.out.println("done()");
            ImportantData data = null;
            try {
                data = get();
            } catch (InterruptedException | ExecutionException | CancellationException ex) {
                System.err.println("done() exception: " + ex);
            }
            label.setText(data != null ? "Retrieved data!" : "Did not retrieve data.");
            progressDialog.setVisible(false);
        }

        /**
         * This pretends to do some data fetching.
         */
        private String someNetworkDataFetching() throws SQLException {
            DriverManager.getConnection("jdbc:mysql://1.1.1.1/db", "user", "pass");
            // Retrieve data...
            return "data chunk";
        }

        /**
         * This tries to create ImportantData object.
         */
        @Override
        protected ImportantData doInBackground() throws Exception {
            // Show the progress bar dialog.
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    dfp.setVisible(true);
                }
            });

            ImportantData data = new ImportantData();
            try {
                int i = 0;
                // There is a network operation here (JDBC data retrieval)
                String chunk1 = someNetworkDataFetching();
                if (isCancelled()) {
                    System.out.println("DataFetcher cancelled.");
                    return null;
                }
                data.addChunk(chunk1);
                publish(++i);

                // And another jdbc data operation....
                String chunk2 = someNetworkDataFetching();
                if (isCancelled()) {
                    System.out.println("DataFetcher cancelled.");
                    return null;
                }
                data.addChunk(chunk2);
                publish(++i);
            } catch (Exception ex) {
                System.err.println("doInBackground() exception: " + ex);
                return null;
            }
            System.out.println("doInBackground() finished");
            return data;
        }
    }

    /**
     * Set up the main window.
     */
    public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        label.setHorizontalAlignment(SwingConstants.CENTER);
        getContentPane().add(label, BorderLayout.CENTER);
        // Add a button starting data fetch.
        JButton retrieveButton = new JButton("Do it!");
        retrieveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                fetchData();
            }
        });
        getContentPane().add(retrieveButton, BorderLayout.EAST);
        setSize(400, 75);
        setLocationRelativeTo(null);
        progressBar.setMaximum(2);
    }

    // Shows new JDialog with a JProgressBar and calls its fetchData()
    public void fetchData() {
        label.setText("Retrieving data...");
        dfp = new DataFetcherProgress(this);
        dfp.fetchData();
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    // Use jdbc mysql driver
                    Class.forName("com.mysql.jdbc.Driver");
                } catch (ClassNotFoundException ex) {
                    ex.printStackTrace();
                    return;
                }

                // Show the Frame
                new Test().setVisible(true);
            }
        });

    }
}

About the only thing I might do different is not use the SwingUtilities.invokeLater in the doInBackground method to show the dialog, but maybe use a PropertyChangeListener to monitor the changes to the state property worker. 关于我可能要做的唯一一件事情是,不使用doInBackground方法中的SwingUtilities.invokeLater来显示对话框,而是可以使用PropertyChangeListener来监视对state属性工作器的更改。

I would also use the PropertyChangeListener to monitor the changes to the progress property of the worker. 我还将使用PropertyChangeListener监视对worker的progress属性的更改。 Instead of using publish to indicate the progression changes I would use the setProgress method (and getProgress in the PropertyChangeListener ) 我将使用setProgress方法(以及PropertyChangeListener getProgress )来代替使​​用publish来指示进度更改。

For example... java swingworker thread to update main Gui 例如... java swingworker线程更新主GUI

I might also consider creating the UI on a JPanel and adding it to the JDialog rather then extending directory from JDialog as it would give the oppurtunity to re-use the panel in other ways, should you wish... 我可能还会考虑在JPanel上创建UI并将其添加到JDialog而不是从JDialog扩展目录,因为如果您愿意的话,它将给您提供以其他方式重用面板的机会。

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

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