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:de.atomfrede.tools.evalutation.tools.plot.ui.wizard.simple.SimplePlotWizard.java

@Override
public void onFinished(List<WizardPage> arg0, WizardSettings arg1) {
    this.setVisible(false);

    busyDialog = new BusyDialog("Please wait while plots are generated...");
    busyDialog.setLocationRelativeTo(DialogUtil.getInstance().getFrame());
    DialogUtil.getInstance().showStandardDialog(busyDialog);

    SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {

        @Override/*from   w  w  w  .  java2s  . c o m*/
        protected Object doInBackground() throws Exception {
            StringBuilder fileNameBuilder = new StringBuilder();
            // first collect all datasets
            List<XYDatasetWrapper> wrappers = ((DatasetSelectionWizardPage) pages.get(1)).getDatasetWrappers();
            XYDatasetWrapper[] wrappersArray = new XYDatasetWrapper[wrappers.size()];

            int width = ((FileSelectionWizardPage) pages.get(0)).getEnteredWidth();
            int height = ((FileSelectionWizardPage) pages.get(0)).getEnteredHeight();

            int i = 0;
            for (XYDatasetWrapper wrapper : wrappers) {
                wrappersArray[i] = wrapper;
                if (i == 0)
                    fileNameBuilder.append(wrapper.getSeriesName());
                else
                    fileNameBuilder.append("-" + wrapper.getSeriesName());
                i++;
            }

            String date = DateFormat.getDateInstance().format(new Date());

            String fileName = date + "-" + fileNameBuilder.toString();
            CustomSimplePlot timePlot = new CustomSimplePlot(dataFile, fileName, width, height, wrappersArray);
            try {
                timePlot.plot();
            } catch (Exception e) {
                log.error("The requested data could not be plotted", e);
            }
            try {
                Desktop.getDesktop().open(new File(Options.getOutputFolder(), fileName + ".pdf"));
            } catch (IOException e) {
                log.error("Generated file could not be opened.", e);
            }

            return null;
        }

        @Override
        protected void done() {
            busyDialog.dispose();
            dispose();
        }

    };

    worker.execute();

}

From source file:ProgressBarDemo.java

/**
 * Called from ProgressBarDemo to start the task.
 *//*from  www.  j av  a  2s  .  c  o m*/
public void go() {
    final SwingWorker worker = new SwingWorker() {
        public Object construct() {
            current = 0;
            done = false;
            canceled = false;
            statMessage = null;
            return new ActualTask();
        }
    };
    worker.start();
}

From source file:de.wusel.partyplayer.gui.PartyPlayer.java

private void play(final SongWrapper song) {
    SwingWorker worker = new SwingWorker() {

        @Override//  ww w  . ja va2 s .  co  m
        protected Object doInBackground() throws Exception {
            if (player.isPlaying()) {
                return null;
            }
            player.play(song);

            return null;
        }
    };
    worker.execute();
}

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

private void doExport() {
    final String workingId = PlatformUI.MIRTH_FRAME.startWorking("Exporting attachment...");

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        private String errorMessage = "";

        public Void doInBackground() {
            boolean binary = binaryButton.isSelected();
            try {
                if (localButton.isSelected()) {
                    AttachmentUtil.writeToFile(fileField.getText(), getSelectedAttachment(), binary);
                } else {
                    PlatformUI.MIRTH_FRAME.mirthClient.exportAttachmentServer(
                            PlatformUI.MIRTH_FRAME.messageBrowser.getChannelId(),
                            PlatformUI.MIRTH_FRAME.messageBrowser.getSelectedMessageId(),
                            PlatformUI.MIRTH_FRAME.messageBrowser.getSelectedAttachmentId(),
                            fileField.getText(), binary);
                }/*  www .  jav  a 2s  . c o m*/
            } catch (Exception e) {
                errorMessage = e.getMessage();
            }

            return null;
        }

        public void done() {
            PlatformUI.MIRTH_FRAME.stopWorking(workingId);
            PlatformUI.MIRTH_FRAME.alertInformation(PlatformUI.MIRTH_FRAME,
                    StringUtils.isBlank(errorMessage)
                            ? "Successfully exported attachment to: " + fileField.getText()
                            : "Failed to export attachment: " + errorMessage);
        }
    };

    worker.execute();
}

From source file:de.atomfrede.tools.evalutation.tools.plot.ui.wizard.time.TimePlotWizard.java

@Override
public void onFinished(List<WizardPage> arg0, WizardSettings arg1) {
    this.setVisible(false);

    busyDialog = new BusyDialog("Please wait while plots are generated...");
    busyDialog.setLocationRelativeTo(DialogUtil.getInstance().getFrame());
    DialogUtil.getInstance().showStandardDialog(busyDialog);

    SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {

        @Override/*from  w w  w  .  j  ava 2s .c  o m*/
        protected Object doInBackground() throws Exception {
            StringBuilder fileNameBuilder = new StringBuilder();
            // first collect all datasets
            List<TimeDatasetWrapper> wrappers = ((DatasetSelectionWizardPage) pages.get(1))
                    .getTimeDatasetWrappers();
            TimeDatasetWrapper[] wrappersArray = new TimeDatasetWrapper[wrappers.size()];

            int width = ((TimeFileSelectionPage) pages.get(0)).getEnteredWidth();
            int height = ((TimeFileSelectionPage) pages.get(0)).getEnteredHeight();

            int i = 0;
            for (TimeDatasetWrapper wrapper : wrappers) {
                wrappersArray[i] = wrapper;
                if (i == 0)
                    fileNameBuilder.append(wrapper.getSeriesName());
                else
                    fileNameBuilder.append("-" + wrapper.getSeriesName());
                i++;
            }

            String date = DateFormat.getDateInstance().format(new Date());

            String fileName = date + "-" + fileNameBuilder.toString();
            CustomTimePlot timePlot = new CustomTimePlot(dataFile, fileName, width, height, wrappersArray);
            try {
                timePlot.plot();
            } catch (Exception e) {
                log.error("The requested data could not be plotted", e);
            }
            try {
                Desktop.getDesktop().open(new File(Options.getOutputFolder(), fileName + ".pdf"));
            } catch (IOException e) {
                log.error("Generated file could not be opened.", e);
            }

            return null;
        }

        @Override
        protected void done() {
            busyDialog.dispose();
            dispose();
        }

    };

    worker.execute();
}

From source file:com.aw.swing.mvp.action.ActionManager.java

public void executeAction(final Action action) {
    atBeginningOfAction(action);//from   w w w . j  a v  a2 s .co m
    AWActionTipPainter.instance().hideTipWindow();
    if (action instanceof RoundTransitionAction) {
        ((RoundTransitionAction) action).setTransitionStoppedWithException(false);
    }

    GridProviderManager gridProviderManager = action.getPst().getGridProviderMgr();
    gridProviderManager.removeEditors();

    try {
        action.checkBasicConditions();
    } catch (FlowBreakSilentlyException ex) {
        logger.info("Exit flow method silently");
        return;
    } catch (AWException ex) {
        logger.error("AW Exception:", ex);
        if (action instanceof RoundTransitionAction) {
            ((RoundTransitionAction) action).setTransitionStoppedWithException(true);
        }
        PainterMessages.paintException(ex);
        return;
    }

    String confirmMsg = action.getConfirmMsg();
    if (StringUtils.hasText(confirmMsg)) {
        boolean isCancelAction = action instanceof CancelAction;
        boolean isFindPst = action.getPst() instanceof FindPresenter;
        boolean isModeReadOnly = ViewMode.MODE_READONLY.equals(action.getPst().getViewMode());
        boolean isShowCancelMsgConfirmation = action.getPst().isShowCancelMsgConfirmation();
        if (!isCancelAction || (isShowCancelMsgConfirmation && !isModeReadOnly && !isFindPst)) {
            if (!MsgDisplayer.showConfirmMessage(confirmMsg)) {
                logger.debug(
                        "The action:<" + action.toString() + ">will not be executed because was not confirmed");
                return;
            }
        }
    }
    try {
        action.checkConditions();
        AWInputVerifier.getInstance().disable();
        Presenter pst = action.getPst();
        if (action.execBinding) {
            pst.setValuesToBean();
        }
        if (action.execValidation) {
            pst.validate();
        }
    } catch (AWException ex) {
        if (action instanceof RoundTransitionAction) {
            ((RoundTransitionAction) action).setTransitionStoppedWithException(true);
        }
        if (ex instanceof FlowBreakSilentlyException) {
            return;
        }
        logger.error("AW Exception:", ex);
        PainterMessages.paintException(ex);
        return;
    } finally {
        AWInputVerifier.getInstance().enable();
    }

    if (action.useMessageBlocker) {
        try {
            if (!SwingUtilities.isEventDispatchThread()) {
                SwingUtilities.invokeAndWait(new Runnable() {
                    public void run() {
                        ProcessMsgBlocker.instance().showMessage("Procesando ...");
                    }
                });
            } else {
                ProcessMsgBlocker.instance().showMessage("Procesando ...");
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }

        SwingWorker swingWorker = new SwingWorker() {
            protected Object doInBackground() throws Exception {
                executeActionInternal(action);
                return null;
            }

            protected void done() {
                ProcessMsgBlocker.instance().removeMessage();
                action.afterExecute();
            }
        };
        swingWorker.execute();

    } else {
        executeActionInternal(action);
        action.afterExecute();
    }
}

From source file:de.tntinteractive.portalsammler.gui.MainDialog.java

private void poll(final Gui gui) {

    this.pollButton.setEnabled(false);

    final Settings settings = this.getStore().getSettings().deepClone();
    final ProgressMonitor progress = new ProgressMonitor(this, "Sammle Daten aus den Quell-Portalen...", "...",
            0, settings.getSize());//ww w  .j  a  va2s. co  m
    progress.setMillisToDecideToPopup(0);
    progress.setMillisToPopup(0);
    progress.setProgress(0);

    final SwingWorker<String, String> task = new SwingWorker<String, String>() {

        @Override
        protected String doInBackground() throws Exception {
            final StringBuilder summary = new StringBuilder();
            int cnt = 0;
            for (final String id : settings.getAllSettingIds()) {
                if (this.isCancelled()) {
                    break;
                }
                cnt++;
                this.publish(cnt + ": " + id);
                final Pair<Integer, Integer> counts = MainDialog.this.pollSingleSource(settings, id);
                summary.append(id).append(": ");
                if (counts != null) {
                    summary.append(counts.getLeft()).append(" neu, ").append(counts.getRight())
                            .append(" schon bekannt\n");
                } else {
                    summary.append("Fehler!\n");
                }
                this.setProgress(cnt);
            }
            MainDialog.this.getStore().writeMetadata();
            return summary.toString();
        }

        @Override
        protected void process(final List<String> ids) {
            progress.setNote(ids.get(ids.size() - 1));
        }

        @Override
        public void done() {
            MainDialog.this.pollButton.setEnabled(true);
            MainDialog.this.table.refreshContents();
            try {
                final String summary = this.get();
                JOptionPane.showMessageDialog(MainDialog.this, summary, "Abruf-Zusammenfassung",
                        JOptionPane.INFORMATION_MESSAGE);
            } catch (final Exception e) {
                gui.showError(e);
            }
        }

    };

    task.addPropertyChangeListener(new PropertyChangeListener() {
        @Override
        public void propertyChange(final PropertyChangeEvent evt) {
            if ("progress".equals(evt.getPropertyName())) {
                progress.setProgress((Integer) evt.getNewValue());
            }
            if (progress.isCanceled()) {
                task.cancel(true);
            }
        }
    });

    task.execute();
}

From source file:DownloadDialog.java

/********************************************************************
 * Constructor: DownloadDialog/*www . j  a  va  2  s  .  com*/
 * Purpose: constructor for download, with necessary references
/*******************************************************************/
public DownloadDialog(final MainApplication context, Scheduler scheduler_Ref, JList courseListSelected_Ref,
        JList courseListAll_Ref) {

    // Basic setup for dialog
    setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
    setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

    setTitle(TITLE);

    // Setup proper references
    this.scheduler = scheduler_Ref;
    this.courseListSelected = courseListSelected_Ref;
    this.courseListAll = courseListAll_Ref;

    // Store available terms
    storeTerms();

    // Constraints
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    c.insets = new Insets(10, 10, 10, 10);
    c.gridx = 0;
    c.gridy = 0;
    c.weightx = 1;
    c.weighty = 0;
    c.gridwidth = 2;

    // Main panel
    panel = new JPanel(new GridBagLayout());

    // Add term select box
    termCB = new JComboBox(termsName.toArray());
    panel.add(termCB, c);

    // Setup username and password labels
    JLabel userL = new JLabel("Username:");
    JLabel passL = new JLabel("Password:");
    c.gridwidth = 1;
    c.gridx = 0;
    c.weightx = 0;

    // Add user label
    c.gridy = 1;
    c.insets = new Insets(5, 10, 0, 10);
    panel.add(userL, c);

    // Add password label
    c.gridy = 2;
    c.insets = new Insets(0, 10, 5, 10);
    panel.add(passL, c);

    // Setup user and pass text fields
    user = new JTextField();
    pass = new JPasswordField();
    c.weightx = 1;
    c.gridx = 1;

    // Add user field
    c.gridy = 1;
    c.insets = new Insets(5, 10, 2, 10);
    panel.add(user, c);

    // Add pass field
    c.gridy = 2;
    c.insets = new Insets(2, 10, 5, 10);
    panel.add(pass, c);

    // Setup login button
    JButton login = new JButton("Login");
    login.addActionListener(this);
    c.insets = new Insets(10, 10, 10, 10);
    c.gridx = 0;
    c.gridy = 3;
    c.gridwidth = 2;
    c.weightx = 1;
    panel.add(login, c);

    // Add panel to main box
    add(panel);

    // Pack the components and give userbox focus
    pack();
    user.requestFocus();

    // Create worker to download courses
    worker = new SwingWorker<Void, Void>() {
        protected Void doInBackground() throws Exception {

            // Reset courses
            scheduler.resetCourses();

            // Constraints
            GridBagConstraints c = new GridBagConstraints();
            c.fill = GridBagConstraints.BOTH;
            c.insets = new Insets(10, 10, 10, 10);
            c.gridx = 0;
            c.weightx = 1;
            c.weighty = 0;

            // Remove all elements
            panel.removeAll();

            // Add status
            JLabel status = new JLabel("Connecting...");
            c.gridy = 0;
            panel.add(status, c);

            // Add progress bar
            JProgressBar progressBar = new JProgressBar(0, SUBJECTS.length);
            c.gridy = 1;
            panel.add(progressBar, c);
            progressBar.setPreferredSize(new Dimension(275, 12));

            // Revalidate, repaint, and pack
            //revalidate();
            repaint();
            pack();

            try {

                // Create client
                DefaultHttpClient client = new DefaultHttpClient();

                // Setup and execute initial login
                HttpGet initialLogin = new HttpGet("http://jweb.kettering.edu/cku1/twbkwbis.P_ValLogin");
                HttpResponse response = client.execute(initialLogin);
                HTMLParser.parse(response);

                // Get current term
                String term = termsValue.get(termCB.getSelectedIndex());

                // Consume entity (cookies)
                HttpEntity entity = response.getEntity();
                if (entity != null)
                    entity.consumeContent();

                // Create post for login
                HttpPost login = new HttpPost("http://jweb.kettering.edu/cku1/twbkwbis.P_ValLogin");

                // Parameters
                List<NameValuePair> parameters = new ArrayList<NameValuePair>();
                parameters.add(new BasicNameValuePair("sid", user.getText()));
                parameters.add(new BasicNameValuePair("PIN", pass.getText()));
                login.setEntity(new UrlEncodedFormEntity(parameters));
                login.setHeader("Referer", "http://jweb.kettering.edu/cku1/twbkwbis.P_ValLogin");

                // Login !
                response = client.execute(login);

                // Store proper cookies
                List<Cookie> cookies = client.getCookieStore().getCookies();

                // Start off assuming logging in failed
                boolean loggedIn = false;

                // Check cookies for successful login
                for (int i = 0; i < cookies.size(); i++)
                    if (cookies.get(i).getName().equals("SESSID"))
                        loggedIn = true;

                // Success?
                if (loggedIn) {

                    // Consumption of feed
                    HTMLParser.parse(response);

                    // Execute GET class list page
                    HttpGet classList = new HttpGet(
                            "http://jweb.kettering.edu/cku1/bwskfcls.p_sel_crse_search");
                    classList.setHeader("Referer", "https://jweb.kettering.edu/cku1/twbkwbis.P_GenMenu");
                    response = client.execute(classList);
                    HTMLParser.parse(response);

                    // Execute GET for course page
                    HttpGet coursePage = new HttpGet(
                            "http://jweb.kettering.edu/cku1/bwckgens.p_proc_term_date?p_calling_proc=P_CrseSearch&p_term="
                                    + term);
                    coursePage.setHeader("Referer",
                            "http://jweb.kettering.edu/cku1/bwskfcls.p_sel_crse_search");
                    response = client.execute(coursePage);
                    HTMLParser.parse(response);

                    // Download every subject's data
                    for (int index = 0; index < SUBJECTS.length; index++) {

                        // Don't download if cancel was pressed
                        if (isCancelled())
                            break;

                        // Update status, progress bar, then store course
                        String subject = SUBJECTS[index];
                        status.setText("Downloading " + subject);
                        progressBar.setValue(index);
                        scheduler.storeDynamicCourse(subject, client, term);
                    }

                    // Update course list data
                    courseListAll.setListData(scheduler.getCourseIDs().toArray());

                    // Clear course list data
                    String[] empty = {};
                    courseListSelected.setListData(empty);
                    context.updatePermutations();
                    context.updateSchedule();

                    // Dispose of dialog if cancelled
                    if (!isCancelled()) {
                        dispose();
                    }

                }

                // Invalid login?
                else {

                    // Update status
                    status.setText("Invalid login.");
                }
            }

            // Failed to download?
            catch (Exception exc) {

                // Show stack trace, and update status
                exc.printStackTrace();
                status.setText("Failed downloading.");
            }

            return null;
        }
    };

    // Setup window close event to be same as cancel
    this.addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosing(WindowEvent e) {

            // Cancel all downloads then dispose
            worker.cancel(true);
            dispose();
        }
    });

    // Make sure dialog is visible
    setLocationRelativeTo(context);
    setVisible(true);

}

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

public void doRefresh() {
    if (PlatformUI.MIRTH_FRAME.alertRefresh()) {
        return;/*from   w  w w. j ava 2  s  . c o m*/
    }

    dashboardRefreshIntervalField.setDocument(new MirthFieldConstraints(3, false, false, true));
    messageBrowserPageSizeField.setDocument(new MirthFieldConstraints(3, false, false, true));
    eventBrowserPageSizeField.setDocument(new MirthFieldConstraints(3, false, false, true));
    userPreferences = Preferences.userNodeForPackage(Mirth.class);
    int interval = userPreferences.getInt("intervalTime", 10);
    dashboardRefreshIntervalField.setText(interval + "");

    int messageBrowserPageSize = userPreferences.getInt("messageBrowserPageSize", 20);
    messageBrowserPageSizeField.setText(messageBrowserPageSize + "");

    int eventBrowserPageSize = userPreferences.getInt("eventBrowserPageSize", 100);
    eventBrowserPageSizeField.setText(eventBrowserPageSize + "");

    if (userPreferences.getBoolean("messageBrowserFormat", true)) {
        formatYesRadio.setSelected(true);
    } else {
        formatNoRadio.setSelected(true);
    }

    if (userPreferences.getBoolean("textSearchWarning", true)) {
        textSearchWarningYesRadio.setSelected(true);
    } else {
        textSearchWarningNoRadio.setSelected(true);
    }

    String importChannelCodeTemplateLibraries = userPreferences.get("importChannelCodeTemplateLibraries", null);
    if (importChannelCodeTemplateLibraries == null) {
        importChannelLibrariesAskRadio.setSelected(true);
    } else if (Boolean.parseBoolean(importChannelCodeTemplateLibraries)) {
        importChannelLibrariesYesRadio.setSelected(true);
    } else {
        importChannelLibrariesNoRadio.setSelected(true);
    }

    String exportChannelCodeTemplateLibraries = userPreferences.get("exportChannelCodeTemplateLibraries", null);
    if (exportChannelCodeTemplateLibraries == null) {
        exportChannelLibrariesAskRadio.setSelected(true);
    } else if (Boolean.parseBoolean(exportChannelCodeTemplateLibraries)) {
        exportChannelLibrariesYesRadio.setSelected(true);
    } else {
        exportChannelLibrariesNoRadio.setSelected(true);
    }

    final String workingId = getFrame().startWorking("Loading " + getTabName() + " settings...");

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

        private String checkForNotifications = null;

        public Void doInBackground() {
            try {
                checkForNotifications = getFrame().mirthClient.getUserPreference(currentUser.getId(),
                        "checkForNotifications");
            } catch (ClientException e) {
                getFrame().alertThrowable(getFrame(), e);
            }
            return null;
        }

        @Override
        public void done() {
            if (checkForNotifications == null || BooleanUtils.toBoolean(checkForNotifications)) {
                checkForNotificationsYesRadio.setSelected(true);
            } else {
                checkForNotificationsNoRadio.setSelected(true);
            }
            getFrame().stopWorking(workingId);
        }
    };

    worker.execute();

    RSTAPreferences rstaPreferences = MirthRSyntaxTextArea.getRSTAPreferences();
    updateShortcutKeyTable(rstaPreferences);
    updateRestoreDefaultsButton();

    AutoCompleteProperties autoCompleteProperties = rstaPreferences.getAutoCompleteProperties();
    autoCompleteIncludeLettersCheckBox.setSelected(autoCompleteProperties.isActivateAfterLetters());
    autoCompleteCharactersField.setText(autoCompleteProperties.getActivateAfterOthers());
    autoCompleteDelayField.setText(String.valueOf(autoCompleteProperties.getActivationDelay()));
}

From source file:es.emergya.ui.gis.HistoryMapViewer.java

public static void enableSaveGpx(final boolean enabled) {
    SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {
        @Override//from w  w  w  .ja va 2s . c o m
        protected Object doInBackground() throws Exception {
            return null;
        }

        @Override
        protected void done() {
            if (saveGpx != null) {
                saveGpx.setEnabled(enabled);
                saveGpx.updateUI();
            }
        }
    };
    sw.execute();
}