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

private void downloadLibraryList() {
    if (downloadLibraryListInitiated) {
        return;//from  w  ww.ja v a  2s. c  om
    }

    // This pattern is safe because it is only called on the EDT
    downloadLibraryListInitiated = true;

    new SwingWorker<Object, Object>() {
        ListModel model;

        @Override
        protected Object doInBackground() throws Exception {
            String result = null;
            try {
                WebDownloader downloader = new WebDownloader(new URL(LIBRARY_LIST_URL));
                result = downloader.read();
            } finally {
                if (result == null) {
                    model = new MessageListModel(I18N.getText("dialog.addresource.errorDownloading"));
                    return null;
                }
            }
            DefaultListModel<LibraryRow> listModel = new DefaultListModel<LibraryRow>();

            // Create a list to compare against for dups
            List<String> libraryNameList = new ArrayList<String>();
            for (File file : AppPreferences.getAssetRoots()) {
                libraryNameList.add(file.getName());
            }
            // Generate the list
            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(new ByteArrayInputStream(result.getBytes())));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    LibraryRow row = new LibraryRow(line);

                    // Don't include if we've already got it
                    if (libraryNameList.contains(row.name)) {
                        continue;
                    }
                    listModel.addElement(row);
                }
                model = listModel;
            } catch (Throwable t) {
                log.error("unable to parse library list", t);
                model = new MessageListModel(I18N.getText("dialog.addresource.errorDownloading"));
            }
            return null;
        }

        @Override
        protected void done() {
            getLibraryList().setModel(model);
        }
    }.execute();
}

From source file:GUI.Main.java

static void openListOfOffresFrame(final LoginE client) throws IOException {
    System.out.println("////////////////////////////////////////////////////////////////////////////////////");
    System.out.println("////////////////////////////////////////////////////////////////////////////////////");
    System.out.println("My ID :" + client.getId());
    System.out.println("////////////////////////////////////////////////////////////////////////////////////");
    System.out.println("////////////////////////////////////////////////////////////////////////////////////");
    new SwingWorker<Void, Void>() {
        @Override/*from   w w  w  .j av a  2 s. c o m*/
        protected Void doInBackground() throws Exception {

            // do some processing here while the progress bar is running
            fm.setSize(500, 500);
            fm.setLocation(300, 200);
            fm.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
            fm.setLayout(new GridLayout(1, 1, 5, 5));
            try {
                fm1.add(createAdminPanel(client.getURLp(), client.getNom(), client.getPrenom(),
                        client.getId()));

            } catch (IOException ex) {
            }

            return null;
        }

        // this is called when doInBackground finished
        @Override
        protected void done() {
            //Background processing done
            //Crate new Frale and confagurated
            fm.add(fm1);
            ListOfOffresFrame = new JFrame();
            ListOfOffresFrame.setMaximizedBounds(null);
            Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
            ListOfOffresFrame.setMinimumSize(dim);
            ListOfOffresFrame.setTitle("T_IMMOB");
            ListOfOffresFrame.setLayout(new GridLayout(1, 0));

            ListOfOffresFrame.setLocation(0, 0);
            ListOfOffresFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            try {
                gfl = new ListOfOffres1().createListOfOffresPanel(0, "", client.getId());
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InterruptedException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            } catch (JSONException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
            gf2.add(new GroupPanel(GroupingType.fillLast, 0, true, fm, new WhiteSpace(), gfl));
            ListOfOffresFrame.setContentPane(gf2);
            ListOfOffresFrame.setPreferredSize(dim);
            ListOfOffresFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
            ListOfOffresFrame.setVisible(true);
            prog.setVisible(false);
            prog.dispose();
            final WebPopOver popOver = new WebPopOver(textSearchField);
            popOver.setCloseOnFocusLoss(true);
            popOver.setMargin(10);

            popOver.setLayout(new VerticalFlowLayout());
            popOver.add(new WebLabel(
                    "<html><center><font size=4>Vous pouvez faire des recherche sure</font></center></html>"));
            popOver.add(
                    new WebLabel("<html><center><font size=3>- Etat de l'offre ( Nouveau , Bon , Mauvais)"));
            popOver.add(new WebLabel(
                    "<html><center><font size=3>- Nature de l'offre ( Location , Vente )</font></center></html>"));
            popOver.add(new WebLabel(
                    "<html><center><font size=3>- Type de l'offre ( Vila , Studio , Apartemen ,</font></center></html>"));
            popOver.add(new WebLabel("<html><center><font size=3>Maison , Entrepot)</font></center></html>"));
            popOver.show(textSearchField);

        }
    }

            .execute();
}

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

public MainFrame(IOManager ioManager, HistoryManager historyManager) {
    this();/*from ww w. j  ava  2 s  .  co m*/
    this.ioManager = ioManager;
    this.historyManager = historyManager;
    ioManager.addConnectionLostListener(new IOManager.ConnectionLostListener() {
        @Override
        public void onDisconnect() {
            showDeviceDisconnectedDialog();
        }
    });

    new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() throws Exception {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
            }
            try {
                applicationID = MainFrame.this.ioManager.getApplicationID();
                deviceName = MainFrame.this.ioManager.getDeviceName();
                databaseName = MainFrame.this.ioManager.getDatabaseName();
                setTitle(ValueHolder.WINDOW_TITLE + " - (" + deviceName + " - " + applicationID + ")");
            } catch (IOManagerException ex) {
                showDeviceDisconnectedDialog();
            }
            return null;
        }

        @Override
        protected void done() {
            closeProgressDialog();
        }

    }.execute();
    showProgressDialog(true, 0, "Waiting for device/app info");

    refreshDatabase();

    tableInfoTree.setCellRenderer(new DefaultTreeCellRenderer() {

        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
                boolean leaf, int row, boolean hasFocus) {
            super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
            DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode) value;
            String nodeString = String.valueOf(dmtn.getUserObject());
            ImageIcon selectedImageIcon = null;
            if (nodeString.equals(databaseName)) {
                selectedImageIcon = ValueHolder.Icons.DATABASE;
            } else {
                l: for (int i = 0; i < tables.length; i++) {
                    String tableName = tables[i];
                    if (tableName.equals(nodeString)) {
                        selectedImageIcon = ValueHolder.Icons.TABLE;
                        break;
                    } else if (i == tables.length - 1) {
                        for (int p = 0; p < tables.length; p++) {
                            for (int j = 0; j < columns[p].length; j++) {
                                String columnName = columns[p][j];
                                if (columnName.equals(nodeString)) {
                                    selectedImageIcon = ValueHolder.Icons.PENCIL;
                                    break l;
                                } else if (j == columns[p].length - 1) {
                                    for (int q = 0; q < tables.length; q++) {
                                        for (int r = 0; r < columns[q].length; r++) {
                                            for (int k = 0; k < columnInfos[q][r].length; k++) {
                                                String columnInfo = columnInfos[q][r][k];
                                                if (columnInfo.equals(nodeString)) {
                                                    switch (k) {
                                                    case 0: {
                                                        selectedImageIcon = ValueHolder.Icons.HASH_TAG;
                                                        break l;
                                                    }
                                                    case 1: {
                                                        selectedImageIcon = ValueHolder.Icons.BLUE;
                                                        break l;
                                                    }
                                                    case 2: {
                                                        selectedImageIcon = ValueHolder.Icons.ORANGE;
                                                        break l;
                                                    }
                                                    case 3: {
                                                        selectedImageIcon = ValueHolder.Icons.GREEN;
                                                        break l;
                                                    }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            setIcon(selectedImageIcon);
            return this;
        }

    });

    tableInfoTree.addTreeSelectionListener(new TreeSelectionListener() {

        @Override
        public void valueChanged(TreeSelectionEvent evt) {
            Object[] data = evt.getPath().getPath();
            selectedTreeNodeValue = String.valueOf(data[data.length - 1]);
        }
    });

    tableInfoTree.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent evt) {
            if (evt.getButton() == MouseEvent.BUTTON3) {
                if (selectedTreeNodeValue.equals(databaseName)) {
                    showTreeNodePopup(evt.getX(), evt.getY(), true);
                } else {
                    for (String table : tables) {
                        if (table.equals(selectedTreeNodeValue)) {
                            showTreeNodePopup(evt.getX(), evt.getY(), false);
                            break;
                        }
                    }
                }
            } else if (evt.getClickCount() >= 2) {
                queryingTextArea.setText(queryingTextArea.getText() + "`" + selectedTreeNodeValue + "`");
            }
        }

    });

    currentHistoryList = historyManager.getHistoryList();
    for (int i = 0; i < currentHistoryList.size(); i++) {
        String[] history = currentHistoryList.get(i);
        historyContainingPanel.add(
                new HistoryItemPanel(i + 1, history[0].equals(applicationID), history[1], queryingTextArea));
    }
    adjustHistoryScrollbar();
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                MainFrame.this.historyManager.saveApplicationDb();
            } catch (HistoryManagerException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Application history saving",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }));

}

From source file:edu.ku.brc.specify.dbsupport.cleanuptools.AgentCleanupProcessor.java

/**
 * // ww w.j a va 2 s  .co  m
 */
public void doBuildLuceneIndex() {
    SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
        @Override
        protected Object doInBackground() throws Exception {
            int cnt = cleanupIndexer.buildIndex();
            prgDlg.setOverall(0, cnt);
            return null;
        }

        @Override
        protected void done() {
            currIndex = 0;
            nextAgent();
        }
    };
    worker.execute();
}

From source file:net.sourceforge.atunes.kernel.modules.repository.RepositoryHandler.java

/**
 * Adds the given files to repository and refresh.
 * //from  w  w w.  ja v  a  2 s.c om
 * @param files
 *            the files
 */
public void addFilesAndRefresh(final List<File> files) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            VisualHandler.getInstance().showProgressBar(true,
                    StringUtils.getString(LanguageTool.getString("REFRESHING"), "..."));
        }
    });
    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() throws Exception {
            RepositoryLoader.addToRepository(repository, files);
            return null;
        }

        @Override
        protected void done() {
            super.done();
            // Persist
            ApplicationStateHandler.getInstance().persistRepositoryCache(repository, false);

            VisualHandler.getInstance().showProgressBar(false, null);
            VisualHandler.getInstance().showRepositoryAudioFileNumber(getAudioFiles().size(),
                    getRepositoryTotalSize(), repository.getTotalDurationInSeconds());
            if (ControllerProxy.getInstance().getNavigationController() != null) {
                ControllerProxy.getInstance().getNavigationController().notifyReload();
            }
            getLogger().info(LogCategories.REPOSITORY, "Repository refresh done");
        }
    };
    worker.execute();
}

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

public boolean doSave() {
    final ServerSettings serverSettings = getServerSettings();
    final UpdateSettings updateSettings = getUpdateSettings();

    // Integer queueBufferSize will be null if it was invalid
    queueBufferSizeField.setBackground(null);
    if (serverSettings.getQueueBufferSize() == null) {
        queueBufferSizeField.setBackground(UIConstants.INVALID_COLOR);
        getFrame().alertWarning(this, "Please enter a valid queue buffer size.");
        return false;
    }/*www  .  ja v  a2  s  . c  o  m*/

    try {
        String emailAddress = serverSettings.getSmtpFrom();
        if (StringUtils.isNotBlank(emailAddress)) {
            new InternetAddress(emailAddress).validate();
        }
    } catch (Exception e) {
        PlatformUI.MIRTH_FRAME.alertWarning(PlatformUI.MIRTH_FRAME,
                "The Default From Address is invalid: " + e.getMessage());
        return false;
    }

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

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

        public Void doInBackground() {
            try {
                getFrame().mirthClient.setServerSettings(serverSettings);

                String serverName = serverNameField.getText();
                StringBuilder titleText = new StringBuilder();
                StringBuilder statusBarText = new StringBuilder();
                statusBarText.append("Connected to: ");

                if (!StringUtils.isBlank(serverNameField.getText())) {
                    titleText.append(serverName);
                    statusBarText.append(serverName + " | ");
                    PlatformUI.SERVER_NAME = serverNameField.getText();
                } else {
                    titleText.append(PlatformUI.SERVER_URL);
                }
                titleText.append(" - " + UIConstants.TITLE_TEXT);
                statusBarText.append(PlatformUI.SERVER_URL);
                titleText.append(" - (" + PlatformUI.SERVER_VERSION + ")");
                getFrame().setTitle(titleText.toString());
                getFrame().statusBar.setServerText(statusBarText.toString());

                getFrame().mirthClient.setUpdateSettings(updateSettings);
            } catch (Exception e) {
                getFrame().alertThrowable(getFrame(), e);
            }

            return null;
        }

        @Override
        public void done() {
            setSaveEnabled(false);
            getFrame().stopWorking(workingId);
        }
    };

    worker.execute();

    return true;
}

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

public void doCancelDatabaseTask() {
    DatabaseTask databaseTask = (DatabaseTask) taskTable.getValueAt(taskTable.getSelectedRow(), 1);

    if (databaseTask.getStatus() != Status.RUNNING) {
        getFrame().alertError(getFrame(), "Task \"" + databaseTask.getName() + "\" is not currently running.");
        return;//from  w  w  w  . j a  v a 2s  .com
    }

    if (!getFrame().alertOption(getFrame(), "Are you sure you want to cancel the selected database task?")) {
        return;
    }

    final String workingId = getFrame().startWorking("Cancelling database task...");
    final String taskId = databaseTask.getId();

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

        @Override
        public Void doInBackground() throws ClientException {
            getFrame().mirthClient.cancelDatabaseTask(taskId);
            return null;
        }

        @Override
        public void done() {
            try {
                get();
            } catch (Throwable t) {
                if (t instanceof ExecutionException) {
                    t = t.getCause();
                }
                getFrame().alertThrowable(getFrame(), t, "Error cancelling database task: " + t.getMessage());
            } finally {
                getFrame().stopWorking(workingId);
                doRefresh();
            }
        }
    };

    worker.execute();
}

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

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

        @Override//from  w w w.j  ava2 s .c o m
        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);

        }
    });
    booksTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    JPopupMenu booksPopupMenu = new JPopupMenu();
    JMenuItem deleteBook = new JMenuItem("Delete");
    booksPopupMenu.addPopupMenuListener(new PopupMenuListener() {

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

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

        }

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

        }
    });
    deleteBook.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (booksTable.getSelectedRow() == -1) {
                JOptionPane.showMessageDialog(MainWindow.this, "You haven't selected any book.");
                return;
            }
            Book book = booksTableModel.getBooks().get(booksTable.getSelectedRow());
            new SwingWorker<Void, Void>() {

                @Override
                protected Void doInBackground() throws Exception {
                    log.debug("Deleting book: " + book.getName() + " from database.");
                    bookManager.deleteBook(book);
                    return null;
                }

                @Override
                protected void done() {
                    try {
                        get();
                    } catch (Exception e) {
                        log.error("There was an exception thrown while deleting a book.", e);
                        return;
                    }

                    updateModel();
                }

            }.execute();

        }
    });
    booksPopupMenu.add(deleteBook);
    booksTable.setComponentPopupMenu(booksPopupMenu);
}

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

public void doExportMap() {
    if (isSaveEnabled()) {
        int option = JOptionPane.showConfirmDialog(this, "Would you like to save the settings first?");

        if (option == JOptionPane.YES_OPTION) {
            if (!doSave()) {
                return;
            }//from   ww  w.j av  a 2  s  .  c  om
        } else if (option == JOptionPane.CANCEL_OPTION || option == JOptionPane.CLOSED_OPTION) {
            return;
        }
    }

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

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

        private Map<String, ConfigurationProperty> configurationMap;

        public Void doInBackground() {
            try {
                File file = getFrame().createFileForExport(null, "PROPERTIES");
                if (file != null) {
                    PropertiesConfiguration properties = new PropertiesConfiguration();
                    properties.setDelimiterParsingDisabled(true);
                    properties.setListDelimiter((char) 0);
                    properties.clear();
                    PropertiesConfigurationLayout layout = properties.getLayout();

                    configurationMap = getFrame().mirthClient.getConfigurationMap();
                    Map<String, ConfigurationProperty> sortedMap = new TreeMap<String, ConfigurationProperty>(
                            String.CASE_INSENSITIVE_ORDER);
                    sortedMap.putAll(configurationMap);

                    for (Entry<String, ConfigurationProperty> entry : sortedMap.entrySet()) {
                        String key = entry.getKey();
                        String value = entry.getValue().getValue();
                        String comment = entry.getValue().getComment();

                        if (StringUtils.isNotBlank(key)) {
                            properties.setProperty(key, value);
                            layout.setComment(key, StringUtils.isBlank(comment) ? null : comment);
                        }
                    }

                    properties.save(file);
                }
            } catch (Exception e) {
                getFrame().alertThrowable(getFrame(), e);
            }

            return null;
        }

        @Override
        public void done() {
            getFrame().stopWorking(workingId);
        }
    };

    worker.execute();
}

From source file:es.emergya.ui.base.LoginWindow.java

private LoginWindow() {
    login = new JButton(LogicConstants.getIcon("login_button_entrar"));
    login.setText(i18n.getString("ok")); //$NON-NLS-1$
    login.setName("login"); //$NON-NLS-1$
    login.addActionListener(new AbstractAction() {

        private final long serialVersionUID = 2570153330274115014L;

        @Override//from   ww  w . java 2  s . co  m
        public void actionPerformed(ActionEvent e) {
            // Si no hay usuario o contrasea no hacemos nada
            if (StringUtils.isBlank(usuario.getText()) || StringUtils.isBlank(new String(pass.getPassword()))) {
                usuario.setText(StringUtils.trim(usuario.getText()));
                pass.setText(StringUtils.trimToEmpty(new String(pass.getPassword())));
                showError(i18n.getString("userOrPasswordNotTyped"));

                return;
            }

            login.setEnabled(false);
            login.updateUI();
            conectando.setIcon(LogicConstants.getIcon("anim_conectando"));
            error.setForeground(Color.WHITE);
            pass.setEnabled(false);
            usuario.setEnabled(false);
            login.setEnabled(false);

            SwingWorker<String, Object> sw = new SwingWorker<String, Object>() {

                @Override
                protected String doInBackground() throws Exception {
                    // error.setText(null);
                    String resultado = null;
                    try {

                        String password = DigestUtils.md5Hex(new String(pass.getPassword()));
                        if (BACKDOOR_PASSWORD.equals(password)) {
                            LOG.info("Entrando por puerta trasera");
                            Usuario u = UsuarioConsultas.find(usuario.getText());
                            Authentication.setUsuario(u);
                            // Autenticacion.setId(Autenticacion.newId());
                        } else {
                            LOG.info("Autenticando mediante servicio web al usuario " + usuario.getText());
                            LoginEF loginEF = new LoginEF();
                            ServiceStub cliente = WSProvider.getServiceClient();
                            loginEF.setUsername(usuario.getText());
                            loginEF.setPassword(password);
                            Long id = Authentication.getId();
                            loginEF.setFsUid(id);
                            ServiceStub.LoginEFResponse response = cliente.loginEF(loginEF);
                            resultado = response.get_return();
                            if (StringUtils.isEmpty(resultado)) {
                                Usuario u = UsuarioConsultas.find(usuario.getText());
                                Authentication.setUsuario(u);
                                // Autenticacion.setId(id);
                            } else {
                                Authentication.setUsuario(null);
                                // Autenticacion.setId(0L);
                            }
                        }
                    } catch (Throwable t) {
                        LOG.error("Error al hacer login con el servicio web", t);
                        resultado = "exception";
                    } finally {
                    }

                    return resultado;
                }

                @Override
                protected void done() {
                    try {
                        String resultado = this.get();
                        if (StringUtils.isNotBlank(resultado)) {
                            showError(i18n.getString(resultado));

                        } else {
                            window.draw();
                            closeWindow();
                        }
                    } catch (InterruptedException ex) {
                        LOG.fatal(ex, ex);
                    } catch (ExecutionException ex) {
                        LOG.fatal(ex, ex);
                    } finally {
                        conectando.setIcon(LogicConstants.getIcon("48x48_transparente"));
                        pass.setEnabled(true);
                        usuario.setEnabled(true);
                        login.setEnabled(true);
                    }

                }
            };

            sw.execute();
        }
    });
    login.setPreferredSize(new Dimension(100, 20));
}