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.t3.client.ui.AddResourceDialog.java

@Override
public boolean commit() {
    if (!super.commit()) {
        return false;
    }/*from ww w  .  j  a va 2  s  .com*/

    // Add the resource
    final List<LibraryRow> rowList = new ArrayList<LibraryRow>();

    switch (model.getTab()) {
    case LOCAL:
        if (StringUtils.isEmpty(model.getLocalDirectory())) {
            TabletopTool.showMessage("dialog.addresource.warn.filenotfound", "Error", JOptionPane.ERROR_MESSAGE,
                    model.getLocalDirectory());
            return false;
        }
        File root = new File(model.getLocalDirectory());
        if (!root.exists()) {
            TabletopTool.showMessage("dialog.addresource.warn.filenotfound", "Error", JOptionPane.ERROR_MESSAGE,
                    model.getLocalDirectory());
            return false;
        }
        if (!root.isDirectory()) {
            TabletopTool.showMessage("dialog.addresource.warn.directoryrequired", "Error",
                    JOptionPane.ERROR_MESSAGE, model.getLocalDirectory());
            return false;
        }
        AppSetup.installLibrary(FileUtil.getNameWithoutExtension(root), root);
        return true;

    case WEB:
        if (StringUtils.isEmpty(model.getUrlName())) {
            TabletopTool.showMessage("dialog.addresource.warn.musthavename", "Error", JOptionPane.ERROR_MESSAGE,
                    model.getLocalDirectory());
            return false;
        }
        // validate the url format so that we don't hit it later
        try {
            new URL(model.getUrl());
        } catch (MalformedURLException e) {
            TabletopTool.showMessage("dialog.addresource.warn.invalidurl", "Error", JOptionPane.ERROR_MESSAGE,
                    model.getUrl());
            return false;
        }
        rowList.add(new LibraryRow(model.getUrlName(), model.getUrl(), -1));
        break;

    case TABLETOPTOOL_SITE:
        List<LibraryRow> selectedRows = getLibraryList().getSelectedValuesList();
        if (selectedRows == null || selectedRows.isEmpty()) {
            TabletopTool.showMessage("dialog.addresource.warn.mustselectone", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return false;
        }
        for (LibraryRow row : selectedRows) {

            //validate the url format
            row.path = LIBRARY_URL + "/" + row.path;
            try {
                new URL(row.path);
            } catch (MalformedURLException e) {
                TabletopTool.showMessage("dialog.addresource.warn.invalidurl", "Error",
                        JOptionPane.ERROR_MESSAGE, row.path);
                return false;
            }
            rowList.add(row);
        }
        break;
    }

    new SwingWorker<Object, Object>() {
        @Override
        protected Object doInBackground() throws Exception {
            for (LibraryRow row : rowList) {
                try {
                    RemoteFileDownloader downloader = new RemoteFileDownloader(new URL(row.path));
                    File tmpFile = downloader.read();
                    AppSetup.installLibrary(row.name, tmpFile.toURL());
                    tmpFile.delete();
                } catch (IOException e) {
                    log.error("Error downloading library: " + e, e);
                    TabletopTool.showInformation("dialog.addresource.warn.couldnotload");
                }
            }
            return null;
        }
    }.execute();
    return true;
}

From source file:cz.muni.fi.javaseminar.kafa.bookregister.gui.MainWindow.java

private void initAuthorsTable() {
    authorsTable.getColumnModel().getColumn(2)
            .setCellEditor(new DatePickerCellEditor(new SimpleDateFormat("dd. MM. yyyy")));
    authorsTable.getColumnModel().getColumn(2).setCellRenderer(new DefaultTableCellRenderer() {

        @Override/*from w  ww . ja  va  2  s .  com*/
        public Component getTableCellRendererComponent(JTable jtable, Object value, boolean selected,
                boolean hasFocus, int row, int column) {

            if (value instanceof Date) {

                // You could use SimpleDateFormatter instead
                value = new SimpleDateFormat("dd. MM. yyyy").format(value);

            }

            return super.getTableCellRendererComponent(jtable, value, selected, hasFocus, row, column);

        }
    });

    authorsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    ListSelectionModel selectionModel = authorsTable.getSelectionModel();
    selectionModel.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            DefaultListSelectionModel source = (DefaultListSelectionModel) e.getSource();
            if (source.getMinSelectionIndex() >= 0) {
                authorsTableModel.setCurrentSlectedIndex(source.getMinSelectionIndex());
            }

            if (!e.getValueIsAdjusting()) {
                booksTableModel.setAuthorIndex(source.getMinSelectionIndex());
            }

        }
    });

    authorsTable.getColumnModel().getColumn(2)
            .setCellEditor(new DatePickerCellEditor(new SimpleDateFormat("dd. MM. yyyy")));
    authorsTable.getColumnModel().getColumn(2).setCellRenderer(new DefaultTableCellRenderer() {

        @Override
        public Component getTableCellRendererComponent(JTable jtable, Object value, boolean selected,
                boolean hasFocus, int row, int column) {

            if (value instanceof Date) {

                // You could use SimpleDateFormatter instead
                value = new SimpleDateFormat("dd. MM. yyyy").format(value);

            }

            return super.getTableCellRendererComponent(jtable, value, selected, hasFocus, row, column);

        }
    });

    JPopupMenu authorsPopupMenu = new JPopupMenu();
    JMenuItem deleteItem = new JMenuItem("Delete");

    authorsPopupMenu.addPopupMenuListener(new PopupMenuListener() {

        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    int rowAtPoint = authorsTable.rowAtPoint(
                            SwingUtilities.convertPoint(authorsPopupMenu, new Point(0, 0), authorsTable));
                    if (rowAtPoint > -1) {
                        authorsTable.setRowSelectionInterval(rowAtPoint, rowAtPoint);
                        authorsTableModel.setCurrentSlectedIndex(rowAtPoint);
                    }
                }
            });
        }

        @Override
        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void popupMenuCanceled(PopupMenuEvent e) {
            // TODO Auto-generated method stub

        }
    });
    deleteItem.addActionListener(new ActionListener() {
        private Author author;

        @Override
        public void actionPerformed(ActionEvent e) {
            new SwingWorker<Void, Void>() {

                @Override
                protected Void doInBackground() throws Exception {
                    author = authorsTableModel.getAuthors().get(authorsTable.getSelectedRow());
                    log.debug("Deleting author: " + author.getFirstname() + " " + author.getSurname()
                            + " from database.");
                    authorManager.deleteAuthor(author);

                    return null;
                }

                @Override
                protected void done() {
                    try {
                        get();
                    } catch (InterruptedException | ExecutionException e) {
                        if (e.getCause() instanceof DataIntegrityViolationException) {
                            JOptionPane.showMessageDialog(MainWindow.this,
                                    "Couldn't delete author; there are still some books assigned to him.",
                                    "Error", JOptionPane.ERROR_MESSAGE);
                        }
                        log.error("There was an exception thrown during deletion author: "
                                + author.getFirstname() + " " + author.getSurname(), e);

                        return;
                    }

                    updateModel();
                }
            }.execute();
        }
    });
    authorsPopupMenu.add(deleteItem);
    authorsTable.setComponentPopupMenu(authorsPopupMenu);
}

From source file:edu.ku.brc.specify.tasks.subpane.lm.LifeMapperPane.java

/**
 * Creates the UI./* ww  w . java2  s. c om*/
 */
@SuppressWarnings("unchecked")
protected void createUI() {
    currentSize = getCurrentSizeSquare();

    searchText = createTextField(25);
    searchSciNameBtn = createI18NButton("LM_SEARCH");
    list = new JList(listModel);
    imgDisplay = new ImageDisplay(IMG_WIDTH, IMG_HEIGHT, false, true);

    imgDisplay.setChangeListener(this);

    wwPanel = new WorldWindPanel(false);
    wwPanel.setPreferredSize(new Dimension(currentSize, currentSize));
    wwPanel.setZoomInMeters(600000.0);

    imgDisplay.setDoShowText(false);

    searchMyDataBtn = createI18NButton("LM_SRCH_SP_DATA");
    myDataTF = UIHelper.createTextField();

    CellConstraints cc = new CellConstraints();

    PanelBuilder pb1 = new PanelBuilder(new FormLayout("p,2px,f:p:g,2px,p", "p"));
    pb1.add(createI18NFormLabel("LM_SRCH_COL"), cc.xy(1, 1));
    pb1.add(searchText, cc.xy(3, 1));
    pb1.add(searchSciNameBtn, cc.xy(5, 1));

    PanelBuilder myPB = new PanelBuilder(new FormLayout("f:p:g,p", "p,2px,p,2px,p"));
    mySepComp = myPB.addSeparator(getResourceString("LM_MYDATA_TITLE"), cc.xyw(1, 1, 2));
    myPB.add(myDataTF, cc.xyw(1, 3, 2));
    myPB.add(searchMyDataBtn, cc.xy(2, 5));

    PanelBuilder pb2 = new PanelBuilder(new FormLayout("MAX(p;300px),2px,f:p:g", "f:p:g,20px,p"));
    pb2.add(createScrollPane(list), cc.xy(1, 1));
    pb2.add(myPB.getPanel(), cc.xy(1, 3));

    PanelBuilder pb3 = new PanelBuilder(new FormLayout("f:p:g,p,f:p:g", "f:p:g,p,4px,p,f:p:g"));
    pb3.add(createI18NLabel("LM_WRLD_OVRVW", SwingConstants.CENTER), cc.xy(2, 2));
    pb3.add(imgDisplay, cc.xy(2, 4));

    PanelBuilder pb4 = new PanelBuilder(new FormLayout("f:p:g,p,f:p:g", "f:p:g,p,4px,p,f:p:g"));
    pb4.add(createI18NLabel("LM_INTRACT_VW", SwingConstants.CENTER), cc.xy(2, 2));
    pb4.add(wwPanel, cc.xy(2, 4));

    PanelBuilder pb5 = new PanelBuilder(new FormLayout("f:p:g", "f:p:g,p,f:p:g"));
    pb5.add(pb3.getPanel(), cc.xy(1, 1));
    pb5.add(pb4.getPanel(), cc.xy(1, 3));

    PanelBuilder pb = new PanelBuilder(new FormLayout("p,8px,f:p:g", "p,8px,f:p:g"), this);
    pb.add(pb1.getPanel(), cc.xyw(1, 1, 3));
    pb.add(pb2.getPanel(), cc.xy(1, 3));
    pb.add(pb5.getPanel(), cc.xy(3, 3));

    updateMyDataUIState(false);

    searchText.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                searchSciNameBtn.doClick();
            }
        }
    });

    myDataTF.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                searchMyDataBtn.doClick();
            }
        }
    });

    list.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                if (list.getSelectedIndex() == -1) {
                    wwPanel.reset();
                    imgDisplay.setImage(blueMarble);

                } else {
                    SwingWorker<Boolean, Boolean> worker = new SwingWorker<Boolean, Boolean>() {
                        @Override
                        protected Boolean doInBackground() throws Exception {
                            if (doResetWWPanel) {
                                wwPanel.reset();
                            }
                            doSearchOccur();
                            return null;
                        }

                        @Override
                        protected void done() {
                            imgDisplay.repaint();
                        }
                    };
                    worker.execute();
                }
            }
        }
    });

    searchMyDataBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    doSearchSpecifyData(myDataTF.getText().trim());
                }
            });

        }
    });

    searchSciNameBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            doSearchGenusSpecies();
        }
    });

    blueMarbleListener = new BufferedImageFetcherIFace() {
        @Override
        public void imageFetched(BufferedImage image) {
            blueMarble = image;
            imgDisplay.setImage(blueMarble);
        }

        @Override
        public void error() {
            blueMarbleTries++;
            if (blueMarbleTries < 5) {
                blueMarbleRetry();
            }
        }
    };

    blueMarbleURL = BG_URL + String.format("WIDTH=%d&HEIGHT=%d", IMG_WIDTH, IMG_HEIGHT);

    pointsMapImageListener = new BufferedImageFetcherIFace() {
        @Override
        public void imageFetched(final BufferedImage image) {
            if (renderImage == null) {
                renderImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, BufferedImage.TYPE_INT_ARGB);
            }
            Graphics2D g2d = renderImage.createGraphics();
            if (g2d != null) {
                g2d.fillRect(0, 0, IMG_WIDTH, IMG_HEIGHT);
                if (blueMarble != null) {
                    g2d.drawImage(blueMarble, 0, 0, null);
                }
                if (image != null) {
                    g2d.drawImage(image, 0, 0, null);
                }
                g2d.dispose();

                imgDisplay.setImage(renderImage);
            }
        }

        @Override
        public void error() {
        }
    };
    blueMarbleRetry();
}

From source file:de.cismet.cids.custom.objecteditors.utils.VermessungUmleitungPanel.java

/**
 * DOCUMENT ME!/*from   www.j ava 2 s  .  com*/
 *
 * @param  createUmleitung  DOCUMENT ME!
 */
private void checkIfLinkDocumentExists(final boolean createUmleitung) {
    final SwingWorker<URL, Void> worker = new SwingWorker<URL, Void>() {

        @Override
        protected void done() {
            try {
                final URL file = get();
                if (createUmleitung) {
                    VermessungUmleitungPanel.this.createLinkFile();
                    return;
                }
                jXBusyLabel1.setBusy(false);
                final CardLayout cl = (CardLayout) pnlControls.getLayout();
                cl.show(pnlControls, "card3");
                if (file != null) {
                    lastCheckedURL = file;
                    editor.successAlert();
                    editor.reloadPictureFromUrl(file);
                } else {
                    // no file exists we need to show a warning...
                    lastCheckedURL = new URL(VermessungsrissWebAccessPictureFinder.getInstance()
                            .getObjectPath(true, getLinkDocument()));
                    editor.warnAlert();
                }
            } catch (InterruptedException ex) {
                LOG.error("Worker Thread interrupter", ex);
                showError();
            } catch (Exception ex) {
                LOG.error("Execution error", ex);
                showError();
            }
        }

        @Override
        protected URL doInBackground() throws Exception {
            final String input = getLinkDocument();
            //                if (!isNummerConsistent(input)) {
            //                    return null;
            //                }
            final boolean isPlatzhalter = input.toLowerCase().startsWith(PLATZHALTER_PREFIX);
            if ((mode == MODE.VERMESSUNGSRISS) && !isPlatzhalter) {
                return null;
            }
            if (isPlatzhalter) {
                return new URL(VermessungsrissWebAccessPictureFinder.getInstance()
                        .getObjectPath(mode == MODE.GRENZNIEDERSCHRIFT, input) + ".jpg");
            } else {
                final List<URL> res;
                final String[] props = parsePropertiesFromLink(input);

                // check if we need to format the flur and the blatt
                if (mode == MODE.VERMESSUNGSRISS) {
                    res = VermessungsrissWebAccessPictureFinder.getInstance().findVermessungsrissPicture(
                            props[0], Integer.parseInt(props[1]), props[2], props[3]);
                } else {
                    res = VermessungsrissWebAccessPictureFinder.getInstance().findGrenzniederschriftPicture(
                            props[0], Integer.parseInt(props[1]), props[2], props[3]);
                }
                if ((res == null) || res.isEmpty()) {
                    return null;
                }
                return res.get(0);
            }
        }
    };
    worker.execute();
}

From source file:biomine.bmvis2.crawling.CrawlSuggestionList.java

private void updateList() {
    final int myVersion = ++curVersion;
    SwingWorker<Void, Void> work = new SwingWorker<Void, Void>() {
        protected Void doInBackground() throws Exception {

            try {
                suggestionQuery.setQuery(query.getText());
                suggestionQuery.updateResult();
            } catch (final IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();//from   w  w  w  .j  a v  a  2  s  .c o  m
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(CrawlSuggestionList.this, e.getMessage());
                    }
                });
                return null;
            }
            // update list in event thread
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    // this thread finished after new thread was started
                    if (myVersion < curVersion)
                        return;
                    itemList.clear();
                    for (NodeType n : suggestionQuery.getResult()) {
                        itemList.add(n);
                        for (NodeItem ni : n.items) {
                            nameMap.put(ni.getCode(), ni.getName());
                            itemList.add(ni);
                        }
                    }
                    list.updateUI();
                }
            });
            return null;
        }
    };

    work.execute();

}

From source file:es.emergya.ui.gis.popups.RouteDialog.java

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource().equals(search)) {
        notification.setForeground(Color.WHITE);
        notification.updateUI();/* w  w w.j a  v  a2  s  .  c  o m*/
        progressIcon.setIcon(iconEnviando);
        search.setEnabled(false);
        clear.setEnabled(false);
        new SwingWorker<Boolean, Object>() {
            List<Way> route = null;

            protected void done() {
                if (route != null && route.size() > 0) {
                    setRoute(route);
                } else {
                    notification.setText(i18n.getString("window.route.notification.noRoute"));
                    notification.setForeground(Color.RED);
                }
                progressIcon.setIcon(iconTransparente);
                clear.setEnabled(true);
                search.setEnabled(true);
                notification.updateUI();
            }

            @Override
            protected Boolean doInBackground() throws Exception {
                try {
                    route = getRoute();
                    return true;
                } catch (Throwable t) {
                    log.error("Error al calcular la ruta", t);
                    notification.setText(i18n.getString("progress.route.error"));
                    notification.setForeground(Color.RED);
                    return false;
                }
            }

        }.execute();

    } else {
        from = null;
        fx.setText("");
        fy.setText("");
        to = null;
        tx.setText("");
        ty.setText("");
        search.setEnabled(false);
        clear.setEnabled(false);

        clearRoute();
        instance.notification.setText(i18n.getString("progress.route.nopoints"));
        instance.notification.setForeground(Color.RED);
        notification.updateUI();
        if (!e.getSource().equals(clear)) {
            setVisible(false);
        }
    }
}

From source file:forge.gui.ImportDialog.java

@SuppressWarnings("serial")
public ImportDialog(final String forcedSrcDir, final Runnable onDialogClose) {
    this.forcedSrcDir = forcedSrcDir;

    _topPanel = new FPanel(new MigLayout("insets dialog, gap 0, center, wrap, fill"));
    _topPanel.setOpaque(false);//  w w  w.  j a v a2s . com
    _topPanel.setBackgroundTexture(FSkin.getIcon(FSkinProp.BG_TEXTURE));

    isMigration = !StringUtils.isEmpty(forcedSrcDir);

    // header
    _topPanel.add(new FLabel.Builder().text((isMigration ? "Migrate" : "Import") + " profile data").fontSize(15)
            .build(), "center");

    // add some help text if this is for the initial data migration
    if (isMigration) {
        final FPanel blurbPanel = new FPanel(new MigLayout("insets panel, gap 10, fill"));
        blurbPanel.setOpaque(false);
        final JPanel blurbPanelInterior = new JPanel(
                new MigLayout("insets dialog, gap 10, center, wrap, fill"));
        blurbPanelInterior.setOpaque(false);
        blurbPanelInterior.add(new FLabel.Builder().text("<html><b>What's this?</b></html>").build(),
                "growx, w 50:50:");
        blurbPanelInterior.add(new FLabel.Builder()
                .text("<html>Over the last several years, people have had to jump through a lot of hoops to"
                        + " update to the most recent version.  We hope to reduce this workload to a point where a new"
                        + " user will find that it is fairly painless to update.  In order to make this happen, Forge"
                        + " has changed where it stores your data so that it is outside of the program installation directory."
                        + "  This way, when you upgrade, you will no longer need to import your data every time to get things"
                        + " working.  There are other benefits to having user data separate from program data, too, and it"
                        + " lays the groundwork for some cool new features.</html>")
                .build(), "growx, w 50:50:");
        blurbPanelInterior.add(
                new FLabel.Builder().text("<html><b>So where's my data going?</b></html>").build(),
                "growx, w 50:50:");
        blurbPanelInterior.add(new FLabel.Builder().text(
                "<html>Forge will now store your data in the same place as other applications on your system."
                        + "  Specifically, your personal data, like decks, quest progress, and program preferences will be"
                        + " stored in <b>" + ForgeConstants.USER_DIR
                        + "</b> and all downloaded content, such as card pictures,"
                        + " skins, and quest world prices will be under <b>" + ForgeConstants.CACHE_DIR
                        + "</b>.  If, for whatever"
                        + " reason, you need to set different paths, cancel out of this dialog, exit Forge, and find the <b>"
                        + ForgeConstants.PROFILE_TEMPLATE_FILE
                        + "</b> file in the program installation directory.  Copy or rename" + " it to <b>"
                        + ForgeConstants.PROFILE_FILE
                        + "</b> and edit the paths inside it.  Then restart Forge and use"
                        + " this dialog to move your data to the paths that you set.  Keep in mind that if you install a future"
                        + " version of Forge into a different directory, you'll need to copy this file over so Forge will know"
                        + " where to find your data.</html>")
                .build(), "growx, w 50:50:");
        blurbPanelInterior.add(new FLabel.Builder().text(
                "<html><b>Remember, your data won't be available until you complete this step!</b></html>")
                .build(), "growx, w 50:50:");

        final FScrollPane blurbScroller = new FScrollPane(blurbPanelInterior, true,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        blurbPanel.add(blurbScroller, "hmin 150, growy, growx, center, gap 0 0 5 5");
        _topPanel.add(blurbPanel, "gap 10 10 20 0, growy, growx, w 50:50:");
    }

    // import source widgets
    final JPanel importSourcePanel = new JPanel(new MigLayout("insets 0, gap 10"));
    importSourcePanel.setOpaque(false);
    importSourcePanel.add(new FLabel.Builder().text("Import from:").build());
    _txfSrc = new FTextField.Builder().readonly().build();
    importSourcePanel.add(_txfSrc, "pushx, growx");
    _btnChooseDir = new FLabel.ButtonBuilder().text("Choose directory...").enabled(!isMigration).build();
    final JFileChooser _fileChooser = new JFileChooser();
    _fileChooser.setMultiSelectionEnabled(false);
    _fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    _btnChooseDir.setCommand(new UiCommand() {
        @Override
        public void run() {
            // bring up a file open dialog and, if the OK button is selected, apply the filename
            // to the import source text field
            if (JFileChooser.APPROVE_OPTION == _fileChooser.showOpenDialog(JOptionPane.getRootFrame())) {
                final File f = _fileChooser.getSelectedFile();
                if (!f.canRead()) {
                    FOptionPane.showErrorDialog("Cannot access selected directory (Permission denied).");
                } else {
                    _txfSrc.setText(f.getAbsolutePath());
                }
            }
        }
    });
    importSourcePanel.add(_btnChooseDir, "h pref+8!, w pref+12!");

    // add change handler to the import source text field that starts up a
    // new analyzer.  it also interacts with the current active analyzer,
    // if any, to make sure it cancels out before the new one is initiated
    _txfSrc.getDocument().addDocumentListener(new DocumentListener() {
        boolean _analyzerActive; // access synchronized on _onAnalyzerDone
        String prevText;

        private final Runnable _onAnalyzerDone = new Runnable() {
            @Override
            public synchronized void run() {
                _analyzerActive = false;
                notify();
            }
        };

        @Override
        public void removeUpdate(final DocumentEvent e) {
        }

        @Override
        public void changedUpdate(final DocumentEvent e) {
        }

        @Override
        public void insertUpdate(final DocumentEvent e) {
            // text field is read-only, so the only time this will get updated
            // is when _btnChooseDir does it
            final String text = _txfSrc.getText();
            if (text.equals(prevText)) {
                // only restart the analyzer if the directory has changed
                return;
            }
            prevText = text;

            // cancel any active analyzer
            _cancel = true;

            if (!text.isEmpty()) {
                // ensure we don't get two instances of this function running at the same time
                _btnChooseDir.setEnabled(false);

                // re-disable the start button.  it will be enabled if the previous analyzer has
                // already successfully finished
                _btnStart.setEnabled(false);

                // we have to wait in a background thread since we can't block in the GUI thread
                final SwingWorker<Void, Void> analyzerStarter = new SwingWorker<Void, Void>() {
                    @Override
                    protected Void doInBackground() throws Exception {
                        // wait for active analyzer (if any) to quit
                        synchronized (_onAnalyzerDone) {
                            while (_analyzerActive) {
                                _onAnalyzerDone.wait();
                            }
                        }
                        return null;
                    }

                    // executes in gui event loop thread
                    @Override
                    protected void done() {
                        _cancel = false;
                        synchronized (_onAnalyzerDone) {
                            // this will populate the panel with data selection widgets
                            final _AnalyzerUpdater analyzer = new _AnalyzerUpdater(text, _onAnalyzerDone,
                                    isMigration);
                            analyzer.run();
                            _analyzerActive = true;
                        }
                        if (!isMigration) {
                            // only enable the directory choosing button if this is not a migration dialog
                            // since in that case we're permanently locked to the starting directory
                            _btnChooseDir.setEnabled(true);
                        }
                    }
                };
                analyzerStarter.execute();
            }
        }
    });
    _topPanel.add(importSourcePanel, "gaptop 20, pushx, growx");

    // prepare import selection panel (will be cleared and filled in later by an analyzer)
    _selectionPanel = new JPanel();
    _selectionPanel.setOpaque(false);
    _topPanel.add(_selectionPanel, "growx, growy, gaptop 10");

    // action button widgets
    final Runnable cleanup = new Runnable() {
        @Override
        public void run() {
            SOverlayUtils.hideOverlay();
        }
    };
    _btnStart = new FButton("Start import");
    _btnStart.setEnabled(false);
    _btnCancel = new FButton("Cancel");
    _btnCancel.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            _cancel = true;
            cleanup.run();
            if (null != onDialogClose) {
                onDialogClose.run();
            }
        }
    });

    final JPanel southPanel = new JPanel(new MigLayout("ax center"));
    southPanel.setOpaque(false);
    southPanel.add(_btnStart, "center, w pref+144!, h pref+12!");
    southPanel.add(_btnCancel, "center, w pref+144!, h pref+12!, gap 72");
    _topPanel.add(southPanel, "growx");
}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopSuggestionField.java

protected SwingWorker<List<?>, Void> createSearchWorker(final String currentSearchString,
        final Map<String, Object> params) {
    final SearchExecutor<?> currentSearchExecutor = this.searchExecutor;
    final int currentAsyncSearchTimeoutMs = this.asyncSearchDelayMs;

    return new SwingWorker<List<?>, Void>() {
        @Override// w  w w.  ja  v a  2 s.  com
        protected List<?> doInBackground() throws Exception {
            Thread.currentThread().setName("ReactiveSearchField_AsyncThread");

            Thread.sleep(currentAsyncSearchTimeoutMs);

            List<?> result;
            try {
                result = asyncSearch(currentSearchExecutor, currentSearchString, params);
            } catch (RuntimeException e) {
                log.error("Error in async search thread", e);

                result = Collections.emptyList();
            }

            return result;
        }

        @Override
        protected void done() {
            super.done();

            List<?> searchResultItems;
            try {
                searchResultItems = get();
            } catch (InterruptedException | ExecutionException | CancellationException e) {
                return;
            }

            log.debug("Search results for '{}'", currentSearchString);

            handleSearchResults(searchResultItems);
        }
    };
}

From source file:GUI.ListOfOffres1.java

static void openListOfOffresFrameagn(final int xmlnn, final String xmln, final int myId) throws IOException {
    WebLookAndFeel.install();//from w w  w .j  a va2  s .  c om
    WebLookAndFeel.setDecorateAllWindows(true);
    openPleaseWait();
    new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() throws Exception {

            // do some processing here while the progress bar is running
            try {

                gf2.removeAll();
                gfl.removeAll();
                gfl.add(createListOfOffresPanel(xmlnn, xmln, myId));

            } catch (IOException ex) {
                Logger.getLogger(ListOfOffres1.class.getName()).log(Level.SEVERE, null, ex);
            }

            return null;
        }

        // this is called when doInBackground finished
        @Override
        protected void done() {
            //Background processing done

            gf2.add(new GroupPanel(GroupingType.fillLast, 0, true, fm, new WhiteSpace(), gfl));
            gf2.revalidate();
            gf2.repaint();
            prog.setVisible(false);

        }
    }

            .execute();

}

From source file:sk.uniza.fri.pds.spotreba.energie.gui.MainGui.java

private void increasedSpendingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_increasedSpendingActionPerformed
    final IncreasedSpendingStatisticParams params = new IncreasedSpendingStatisticParams();
    int option = showUniversalInputDialog(params, "Zven spotreba");
    if (option == JOptionPane.OK_OPTION) {

        new SwingWorker<List, RuntimeException>() {
            @Override/*from   ww w.  ja  v  a  2  s.  c o m*/
            protected List doInBackground() throws Exception {
                try {
                    return SeHistoriaService.getInstance().getIncreasedSpendingStatistics(params, 1.2);
                } catch (RuntimeException e) {
                    publish(e);
                    return null;
                }
            }

            @Override
            protected void done() {
                try {
                    List data = get();
                    showJTable(ZvysenieSpotreby.class, data);
                } catch (InterruptedException | ExecutionException ex) {
                    Logger.getLogger(MainGui.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            @Override
            protected void process(List<RuntimeException> chunks) {
                if (chunks.size() > 0) {
                    showException("Chyba", chunks.get(0));
                }
            }
        }.execute();
    }
}