Example usage for javax.swing SwingWorker SwingWorker

List of usage examples for javax.swing SwingWorker SwingWorker

Introduction

In this page you can find the example usage for javax.swing SwingWorker SwingWorker.

Prototype

public SwingWorker() 

Source Link

Document

Constructs this SwingWorker .

Usage

From source file:com.josescalia.tumblr.form.TumblrImageViewer.java

private void btnAddToCollectionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddToCollectionActionPerformed
    frame = (MainFrame) this.getTopLevelAncestor();
    form = this;//from  w w  w .j  a  v a2 s  .  c  o  m
    if (validateUrl()) {
        final Rss rss = constructNewObject();

        if (rss != null) {
            //set Progressbar and cursor
            form.setCursor(new Cursor(Cursor.WAIT_CURSOR));
            frame.setCursor(new Cursor(Cursor.WAIT_CURSOR));
            frame.startProgressBar("Saving");

            new SwingWorker<Boolean, Boolean>() {
                @Override
                protected Boolean doInBackground() throws Exception {
                    try {
                        rssService.save(rss);
                        return Boolean.TRUE;
                    } catch (Exception e) {
                        UIAlert.showError(null, UIMessageConstants.saveFailedMsg + "\n" + e.getMessage());
                    }
                    return Boolean.FALSE;
                }

                protected void done() {
                    try {
                        if (get()) {
                            UIAlert.showInformation(null, UIMessageConstants.saveSucceedMsg);
                        } else {
                            UIAlert.showInformation(null, UIMessageConstants.saveFailedMsg);
                        }
                    } catch (InterruptedException e) {
                        logger.error(e);
                    } catch (ExecutionException e) {
                        logger.error(e);
                    }
                    form.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                    frame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                    frame.stopProgressBar("");
                }
            }.execute();

        }
    }
}

From source file:com.nbt.TreeFrame.java

public void doImportDat(final File file) {
    Cursor waitCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
    setCursor(waitCursor);/*ww w  . j  ava2 s.  c o  m*/

    SwingWorkerUnlimited.execure(new SwingWorker<CompoundTag, Void>() {

        @Override
        protected CompoundTag doInBackground() throws Exception {
            NBTInputStream ns = null;
            try {
                ns = new NBTInputStream(new FileInputStream(file));
                return (CompoundTag) ns.readTag();
            } finally {
                IOUtils.closeQuietly(ns);
            }
        }

        @Override
        protected void done() {
            CompoundTag tag = null;
            try {
                tag = get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
                Throwable cause = ExceptionUtils.getRootCause(e);
                showErrorDialog(cause.getMessage());
                return;
            }
            textFile.setText(file.getAbsolutePath());

            updateTreeTable(tag);

            Cursor defaultCursor = Cursor.getDefaultCursor();
            setCursor(defaultCursor);
        }

    });
}

From source file:com.mirth.connect.client.ui.browsers.message.MessageBrowser.java

public void loadPageNumber(final int pageNumber) {
    final String workingId = parent.startWorking("Loading page...");

    if (worker != null && !worker.isDone()) {
        parent.mirthClient.getServerConnection().abort(getAbortOperations());
        worker.cancel(true);/* w w w.  ja  v a2  s  .  c o m*/
    }

    filterButton.setEnabled(false);
    nextPageButton.setEnabled(false);
    previousPageButton.setEnabled(false);
    countButton.setEnabled(false);
    pageGoButton.setEnabled(false);

    // Give focus to the message tree table since these buttons will lose focus. That way the user can also immediately use the arrow keys after a search.
    messageTreeTable.requestFocus();

    worker = new SwingWorker<Void, Void>() {
        private boolean foundItems = false;
        private int retrievedPageNumber = 1;

        public Void doInBackground() {

            try {
                foundItems = messages.loadPageNumber(pageNumber);
            } catch (Throwable t) { // catch Throwable in case the client runs out of memory

                if (t.getMessage().contains("Java heap space")) {
                    parent.alertError(parent,
                            "There was an out of memory error when trying to retrieve messages.\nIncrease your heap size or decrease your page size and search again.");
                } else if (t instanceof RequestAbortedException) {
                    // The client is no longer waiting for the search request
                } else {
                    parent.alertThrowable(parent, t);
                }
                cancel(true);
            }

            return null;
        }

        public void done() {
            if (!isCancelled()) {
                boolean enableCountButton = (messages.getItemCount() == null);

                deselectRows();
                tableModel.clear();

                if (foundItems) {

                    // if there are no results for pageNumber, loadPageNumber will recursively check previous pages
                    // so we must get the retrievedPageNumber from messages to use below.
                    retrievedPageNumber = messages.getPageNumber();
                    pageNumberField.setText(String.valueOf(retrievedPageNumber));

                    for (Message message : messages) {
                        tableModel.addMessage(message);
                    }

                    if (!messages.hasNextPage()) {
                        messages.setItemCount(new Long(
                                ((retrievedPageNumber - 1) * messages.getPageSize()) + messages.size()));
                        enableCountButton = false;
                    }
                } else {
                    messages.setItemCount(new Long((retrievedPageNumber - 1) * messages.getPageSize()));
                    enableCountButton = false;
                    pageNumberField.setText("0");
                }

                messageTreeTable.expandAll();

                updatePagination();

                if (enableCountButton) {
                    countButton.setEnabled(true);
                }
            }
            filterButton.setEnabled(true);
            parent.stopWorking(workingId);
        }
    };

    worker.execute();
}

From source file:com.nbt.TreeFrame.java

public void doImportMCR(final File file) {
    Cursor waitCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
    setCursor(waitCursor);/*from  w w  w .  j a v  a2 s . c om*/

    SwingWorkerUnlimited.execure(new SwingWorker<Region, Void>() {

        @Override
        protected Region doInBackground() throws Exception {
            NBTRegion region = new NBTRegion(file);
            region.getChunks(); // load from disk
            return region;
        }

        @Override
        protected void done() {
            Region region = null;
            try {
                region = get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
                Throwable cause = ExceptionUtils.getRootCause(e);
                showErrorDialog(cause.getMessage());
                return;
            }
            textFile.setText(file.getAbsolutePath());

            updateTreeTable(region);

            Cursor defaultCursor = Cursor.getDefaultCursor();
            setCursor(defaultCursor);
        }

    });
}

From source file:com.mirth.connect.client.ui.ChannelPanel.java

public void doRedeployAll() {
    if (!parent.alertOption(parent, "Are you sure you want to redeploy all channels?")) {
        return;//  w w  w . j ava 2 s .co  m
    }

    final String workingId = parent.startWorking("Deploying channels...");
    parent.dashboardPanel.deselectRows(false);
    parent.doShowDashboard();

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        @Override
        public Void doInBackground() {
            try {
                parent.mirthClient.redeployAllChannels();
            } catch (ClientException e) {
                parent.alertThrowable(parent, e);
            }
            return null;
        }

        @Override
        public void done() {
            parent.stopWorking(workingId);
            parent.doRefreshStatuses(true);
        }
    };

    worker.execute();
}

From source file:com.josescalia.tumblr.form.TumblrImageViewer.java

private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoadActionPerformed
    frame = (MainFrame) this.getTopLevelAncestor();
    form = this;//from  w w w. j  a v  a2 s .c om

    //busy cursor and progress bar in frame and panel
    form.setCursor(new Cursor(Cursor.WAIT_CURSOR));
    frame.setCursor(new Cursor(Cursor.WAIT_CURSOR));
    frame.startProgressBar("Processing");

    new SwingWorker<JDialog, JDialog>() {
        @Override
        protected JDialog doInBackground() throws Exception {
            return new TumblrFavLinkListDialog(null, true);
        }

        @Override
        protected void done() {
            TumblrFavLinkListDialog dlg = null;
            String urlToFetch = "";
            try {
                dlg = (TumblrFavLinkListDialog) get();
                dlg.showDialog();
            } catch (InterruptedException e) {
                logger.error(e);
            } catch (ExecutionException e) {
                logger.error(e);
            }
            if (dlg != null) {
                form.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                frame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                frame.stopProgressBar("");
                urlToFetch = dlg.getFieldText();
            }
            if (!urlToFetch.equals("")) {
                setUrl(urlToFetch);
            }
        }
    }.execute();

}

From source file:com.clough.android.adbv.view.MainFrame.java

private void showTreeNodePopup(int x, int y, boolean isDatabasePopup) {
    JPopupMenu treeNodePopup = new JPopupMenu();
    if (isDatabasePopup) {
        JMenuItem newTableMenuItem = new JMenuItem("New table");
        newTableMenuItem.addActionListener(new ActionListener() {

            @Override//  www.  ja va2  s. c  o  m
            public void actionPerformed(ActionEvent e) {
                System.out.println("new table");
                new CreateTableDialog(MainFrame.this, true).setVisible(true);
                if (tableQueryList != null && tableQueryList.size() > 0) {
                    for (String query : tableQueryList.values()) {
                        inputQuery = query;
                        runQuery();
                    }
                    refreshDatabase();
                    tableQueryList = null;
                }
            }
        });
        treeNodePopup.add(newTableMenuItem);
    } else {
        JMenuItem viewAllMenuItem = new JMenuItem("View table");
        viewAllMenuItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("view all");
                inputQuery = "select * from `" + selectedTreeNodeValue + "`";
                queryingTextArea.setText(inputQuery);
                runQuery();
            }
        });
        treeNodePopup.add(viewAllMenuItem);
        JMenuItem dropTableMenuItem = new JMenuItem("Drop table");
        dropTableMenuItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("drop table");
                if (JOptionPane.showConfirmDialog(null,
                        "All the data in table " + selectedTreeNodeValue
                                + " will be lost!\nClick OK to delete the table",
                        "Sqlite table dropping", JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) {
                    inputQuery = "drop table `" + selectedTreeNodeValue + "`";
                    queryingTextArea.setText(inputQuery);
                    runQuery();
                    refreshDatabase();
                }
            }
        });
        treeNodePopup.add(dropTableMenuItem);
        JMenuItem updateTableMenuItem = new JMenuItem("Update table");
        updateTableMenuItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                System.out.println("update table");

                final Object[] columnsOfTable = getColumnsOfTable(selectedTreeNodeValue);

                new SwingWorker<Void, Void>() {
                    String result;

                    @Override
                    protected Void doInBackground() throws Exception {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException ex) {
                        }
                        result = ioManager.executeQuery("select * from `" + selectedTreeNodeValue + "`");
                        return null;
                    }

                    @Override
                    protected void done() {
                        closeProgressDialog();
                        new UpdateTableDialog(MainFrame.this, true, result, selectedTreeNodeValue,
                                columnsOfTable).setVisible(true);
                    }

                }.execute();
                showProgressDialog(true, 0, "Recieving data from table " + selectedTreeNodeValue);

                if ((rowsToInsert != null && rowsToInsert.size() > 0)
                        || (rowsToUpdate != null && rowsToUpdate.size() > 0)
                        || (rowsToDelete != null && rowsToDelete.size() > 0)) {
                    new SwingWorker<Void, Void>() {

                        @Override
                        protected Void doInBackground() {
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException ex) {
                            }
                            String result = "";
                            try {
                                for (Row row : rowsToInsert) {
                                    String insertQuery = createTableInsertQuery(selectedTreeNodeValue, row);
                                    System.out.println("insertQuery : " + insertQuery);
                                    result = ioManager.executeQuery(insertQuery);
                                    if (result.equals("[]")) {
                                        waitingDialog.incrementProgressBar();
                                    } else {
                                        throw new Exception();
                                    }
                                }
                                for (Row row : rowsToUpdate) {
                                    String updateQuery = createTableUpdateQuery(selectedTreeNodeValue, row);
                                    System.out.println("updateQuery : " + updateQuery);
                                    result = ioManager.executeQuery(updateQuery);
                                    if (result.equals("[]")) {
                                        waitingDialog.incrementProgressBar();
                                    } else {
                                        throw new Exception();
                                    }
                                }
                                for (Row row : rowsToDelete) {
                                    String deleteQuery = createTableDeleteQuery(selectedTreeNodeValue, row);
                                    System.out.println("deleteQuery : " + deleteQuery);
                                    result = ioManager.executeQuery(deleteQuery);
                                    if (result.equals("[]")) {
                                        waitingDialog.incrementProgressBar();
                                    } else {
                                        throw new Exception();
                                    }
                                }
                            } catch (Exception ex) {
                                JOptionPane.showMessageDialog(null, result, "Result error",
                                        JOptionPane.ERROR_MESSAGE);
                            }
                            return null;
                        }

                        @Override
                        protected void done() {
                            closeProgressDialog();
                            refreshDatabase();
                            rowsToInsert = null;
                            rowsToUpdate = null;
                            rowsToDelete = null;
                        }

                    }.execute();
                    showProgressDialog(false, rowsToInsert.size() + rowsToUpdate.size() + rowsToDelete.size(),
                            "Applying changes to the dialog " + selectedTreeNodeValue);
                }

            }
        });
        treeNodePopup.add(updateTableMenuItem);
        JMenuItem copyCreateStatementMenuItem = new JMenuItem("Copy create statement");
        copyCreateStatementMenuItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("copy create statement");
                for (int i = 0; i < tables.length; i++) {
                    if (tables[i].equals(selectedTreeNodeValue)) {
                        StringSelection selection = new StringSelection(queries[i]);
                        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
                        JOptionPane.showMessageDialog(null,
                                "Copied create statement of the table `" + selectedTreeNodeValue
                                        + "` to the clipboard",
                                "Copy create statement", JOptionPane.INFORMATION_MESSAGE);
                        break;
                    }
                }
            }
        });
        treeNodePopup.add(copyCreateStatementMenuItem);
        JMenuItem copyColumnNamesMenuItem = new JMenuItem("Copy column names");
        copyColumnNamesMenuItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("copy column names");
                for (int i = 0; i < tables.length; i++) {
                    if (tables[i].equals(selectedTreeNodeValue)) {
                        String columnNames = "";
                        for (String column : columns[i]) {
                            columnNames = columnNames.concat(column + ",");
                        }
                        StringSelection selection = new StringSelection(
                                columnNames.substring(0, columnNames.length() - 1));
                        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
                        JOptionPane.showMessageDialog(null,
                                "Copied create statement of the table `" + selectedTreeNodeValue
                                        + "` to the clipboard",
                                "Copy create statement", JOptionPane.INFORMATION_MESSAGE);
                        break;
                    }
                }
            }
        });
        treeNodePopup.add(copyColumnNamesMenuItem);
    }

    treeNodePopup.show(tableInfoTree, x, y);
}

From source file:com.nbt.TreeFrame.java

public void doImportDirectory(final File base) {
    Cursor waitCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
    setCursor(waitCursor);//from  w ww.  j  a v a2 s  .  c  o  m

    SwingWorkerUnlimited.execure(new SwingWorker<NBTBranch, Void>() {

        @Override
        protected NBTBranch doInBackground() throws Exception {
            return createBranch(base);
        }

        // TODO: avoid duplicate code in NBTFileBranch#createBranchCache()
        private NBTBranch createBranch(File file) {
            String[] names = file.list();
            if (ArrayUtils.contains(names, WorldDirectory.DIRECTORY_REGION))
                return new NBTWorld(file);
            return new NBTFileBranch(file);
        }

        @Override
        protected void done() {
            NBTBranch branch = null;
            try {
                branch = get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
                Throwable cause = ExceptionUtils.getRootCause(e);
                showErrorDialog(cause.getMessage());
                return;
            }
            textFile.setText(base.getAbsolutePath());

            updateTreeTable(branch);

            Cursor defaultCursor = Cursor.getDefaultCursor();
            setCursor(defaultCursor);
        }

    });
}

From source file:edu.ku.brc.specify.tools.l10nios.StrLocalizerAppForiOS.java

private void scanSources() {
    scanMI.setEnabled(false);// w w  w  .jav  a  2  s.  c o m

    final String STATUSBAR_NAME = "STATUS";
    final JStatusBar statusBar = UIRegistry.getStatusBar();
    statusBar.setProgressRange(STATUSBAR_NAME, 0, 100);

    SwingWorker<Integer, Integer> translator = new SwingWorker<Integer, Integer>() {
        @Override
        protected Integer doInBackground() throws Exception {
            doScanSources();
            return null;
        }

        @Override
        protected void done() {
            scanMI.setEnabled(false);
        }
    };

    translator.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if ("progress".equals(evt.getPropertyName())) {
                statusBar.setText(String.format("%d / 100 ", (Integer) evt.getNewValue()) + "%");
            }
        }
    });
    translator.execute();
}

From source file:com.josescalia.tumblr.form.TumblrImageViewer.java

private void btnFetchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFetchActionPerformed
    frame = (MainFrame) this.getTopLevelAncestor();
    form = this;/* ww  w. java  2 s .c o m*/
    validateUrl();

    //busy cursor and progress bar
    form.setCursor(new Cursor(Cursor.WAIT_CURSOR));
    frame.setCursor(new Cursor(Cursor.WAIT_CURSOR));
    frame.startProgressBar("Fetching");

    new SwingWorker<RssHeader, RssHeader>() {
        @Override
        protected RssHeader doInBackground() throws Exception {
            return service.getRssHeader(url + "/rss");
        }

        protected void done() {
            try {
                setRssHeader(get());
            } catch (InterruptedException e) {
                logger.error(e);
            } catch (ExecutionException e) {
                logger.error(e);
            }
            form.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            frame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            frame.stopProgressBar("");
        }
    }.execute();
}