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.mirth.connect.client.ui.NotificationDialog.java

private void loadNotifications() {
    // Get user preferences
    Set<String> preferenceNames = new HashSet<String>();
    preferenceNames.add("firstlogin");
    preferenceNames.add("checkForNotifications");
    preferenceNames.add("showNotificationPopup");
    preferenceNames.add("archivedNotifications");
    try {/*from  w  w w.  jav  a 2  s .c o  m*/
        userPreferences = parent.mirthClient.getUserPreferences(parent.getCurrentUser(parent).getId(),
                preferenceNames);
    } catch (ClientException e) {
    }
    String archivedNotificationString = userPreferences.getProperty("archivedNotifications");
    if (archivedNotificationString != null) {
        archivedNotifications = ObjectXMLSerializer.getInstance().deserialize(archivedNotificationString,
                Set.class);
    }
    showNotificationPopup = userPreferences.getProperty("showNotificationPopup");
    checkForNotifications = userPreferences.getProperty("checkForNotifications");

    // Build UI
    initComponents();

    // Pull notifications
    final String workingId = parent.startWorking("Loading notifications...");

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        List<Notification> notifications = new ArrayList<Notification>();

        public Void doInBackground() {
            try {
                notifications = ConnectServiceUtil.getNotifications(PlatformUI.SERVER_ID,
                        PlatformUI.SERVER_VERSION, LoadedExtensions.getInstance().getExtensionVersions(),
                        PlatformUI.HTTPS_PROTOCOLS, PlatformUI.HTTPS_CIPHER_SUITES);
            } catch (Exception e) {
                PlatformUI.MIRTH_FRAME.alertError(PlatformUI.MIRTH_FRAME,
                        "Failed to retrieve notifications. Please try again later.");
            }
            return null;
        }

        public void done() {
            notificationModel.setData(notifications);

            for (Notification notification : notifications) {
                if (archivedNotifications.contains(notification.getId())) {
                    notificationModel.setArchived(true, notifications.indexOf(notification));
                } else {
                    unarchivedCount++;
                }
            }
            updateUnarchivedCountLabel();
            list.setModel(notificationModel);
            list.setSelectedIndex(0);
            parent.stopWorking(workingId);
        }
    };

    worker.execute();
}

From source file:net.openbyte.gui.CreateProjectFrame.java

private void button1ActionPerformed(ActionEvent e) {
    if (!(Launch.nameToSolution.get(textField1.getText()) == null)) {
        JOptionPane.showMessageDialog(this, "Project has already been created.", "Error",
                JOptionPane.ERROR_MESSAGE);
        return;//  ww w. jav  a2  s  .c o m
    }
    ModificationAPI modificationAPI = ModificationAPI.MINECRAFT_FORGE;
    String apiName = (String) comboBox1.getSelectedItem();
    if (apiName.equals("MCP")) {
        modificationAPI = ModificationAPI.MCP;
    }
    if (apiName.equals("Bukkit")) {
        modificationAPI = ModificationAPI.BUKKIT;
    }
    MinecraftVersion minecraftVersion = MinecraftVersion.BOUNTIFUL_UPDATE;
    if (((String) comboBox2.getSelectedItem()).equals("1.7.10")) {
        minecraftVersion = MinecraftVersion.THE_UPDATE_THAT_CHANGED_THE_WORLD;
    }
    if (modificationAPI == ModificationAPI.MCP) {
        minecraftVersion = MinecraftVersion.COMBAT_UPDATE;
        String version = (String) comboBox2.getSelectedItem();
        if (version.equals("1.8.9")) {
            minecraftVersion = MinecraftVersion.BOUNTIFUL_UPDATE;
        }
        if (version.equals("1.7.10")) {
            minecraftVersion = MinecraftVersion.THE_UPDATE_THAT_CHANGED_THE_WORLD;
        }
    }
    if (modificationAPI == ModificationAPI.BUKKIT) {
        minecraftVersion = MinecraftVersion.COMBAT_UPDATE;
    }
    this.version = minecraftVersion;
    this.api = modificationAPI;
    setVisible(false);
    //JOptionPane.showMessageDialog(this, "We're working on setting up the project. When we are ready, a window will show up.", "Working on project creation", JOptionPane.INFORMATION_MESSAGE);
    this.projectName = textField1.getText();
    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() throws Exception {
            doOperations();
            return null;
        }
    };
    monitor.setMillisToPopup(0);
    monitor.setMillisToDecideToPopup(0);
    monitor.setProgress(1);
    worker.execute();
    if (monitor.isCanceled()) {
        projectFolder.delete();
        new File(Files.WORKSPACE_DIRECTORY, projectName + ".openproj").delete();
        return;
    }
}

From source file:org.astrojournal.gui.AJMainGUI.java

/**
 * Create the astro journals./*from w  ww  .  ja  v a 2s . c om*/
 */
public void createJournals() {

    if (mainPanel.getComponent(0) instanceof WelcomePanel) {
        // Replace the welcome panel with the output panel
        remove(mainPanel);
        mainPanel.remove(welcomePanel);
        mainPanel.add(outputPanel, BorderLayout.CENTER);
        add(mainPanel);
    }

    // define a SwingWorker to run in background
    // In this way the output is printed gradually as it is
    // generated.
    SwingWorker<String, Void> worker = new SwingWorker<String, Void>() {
        @Override
        public String doInBackground() {
            setStatusPanelText(resourceBundle.getString("AJ.lblFileGenerationinProgressLong.text"));
            cleanJTextPane();
            btnCreateJournal.setEnabled(false);
            btnOpenJournal.setEnabled(false);
            menu.setEnabled(AJGUIActions.CREATE_JOURNAL.name(), false);
            menu.setEnabled(AJGUIActions.OPEN_JOURNAL.name(), false);
            menu.setEnabled(AJGUIActions.EDIT_PREFERENCES.name(), false);
            if (!ajMainControls.createJournal()) {
                setStatusPanelText(resourceBundle.getString("AJ.errPDFLatexShort.text"));
            } else {
                btnOpenJournal.setEnabled(true);
                menu.setEnabled(AJGUIActions.OPEN_JOURNAL.name(), true);
            }
            btnCreateJournal.setEnabled(true);
            menu.setEnabled(AJGUIActions.CREATE_JOURNAL.name(), true);
            menu.setEnabled(AJGUIActions.EDIT_PREFERENCES.name(), true);
            return "";
        }
    };
    // execute the background thread
    worker.execute();
}

From source file:edu.ku.brc.specify.config.FixAttachments.java

/**
 * @param resultsHashMap//w  w  w  . j  a v  a  2s .c o  m
 * @param tableHash
 * @param totalFiles
 */
private void reattachFiles(final HashMap<Integer, Vector<Object[]>> resultsHashMap,
        final HashMap<Integer, AttchTableModel> tableHash, final int totalFiles) {
    final String CNT = "CNT";
    final SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {
        int filesCnt = 0;

        @Override
        protected Integer doInBackground() throws Exception {
            DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession();
            if (session != null) {
                try {
                    for (int tblId : resultsHashMap.keySet()) {
                        AttchTableModel model = tableHash.get(tblId);
                        int cnt = 0;
                        for (int r = 0; r < model.getRowCount(); r++) {
                            if (model.isRecoverable(r)) {
                                Thread.sleep(100);

                                session.beginTransaction();
                                Integer attachID = model.getAttachmentId(r);
                                Attachment attachment = session.get(Attachment.class, attachID);
                                AttachmentUtils.getAttachmentManager()
                                        .setStorageLocationIntoAttachment(attachment, false);
                                try {
                                    attachment.storeFile(true); // false means do not display an error dialog
                                    session.saveOrUpdate(attachment);
                                    session.commit();
                                    model.setRecovered(r, true);
                                    filesCnt++;

                                } catch (IOException ex) {
                                    session.rollback();
                                }
                            }
                            cnt++;
                            firePropertyChange(CNT, 0, (int) ((double) cnt / (double) totalFiles * 100.0));
                        }
                    }
                } catch (Exception ex) {
                    session.rollback();

                } finally {
                    session.close();
                }
            }
            return null;
        }

        @Override
        protected void done() {
            UIRegistry.clearSimpleGlassPaneMsg();
            UIRegistry.displayInfoMsgDlg(String.format("Files recovered: %d / %d", filesCnt, totalFiles));

            File file = produceSummaryReport(resultsHashMap, tableHash, totalFiles);
            if (file != null) {
                try {
                    AttachmentUtils.openFile(file);
                } catch (Exception e) {
                }
            }

            if (getNumberofBadAttachments() == 0) {
                AppPreferences.getGlobalPrefs().putBoolean("CHECK_ATTCH_ERR", true);
            }
            super.done();
        }
    };

    final SimpleGlassPane glassPane = UIRegistry
            .writeSimpleGlassPaneMsg(String.format("Recovering %d files.", totalFiles), 24);
    glassPane.setProgress(0);

    worker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if (CNT.equals(evt.getPropertyName())) {
                glassPane.setProgress((Integer) evt.getNewValue());
            }
        }
    });

    worker.execute();
}

From source file:es.emergya.ui.plugins.LayerSelectionDialog.java

private void initOptions(final JPanel list) {
    SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {

        @Override/* w  ww  .  j  a v a2s  .  c om*/
        protected Object doInBackground() throws Exception {
            publish(new Object[0]);
            for (CapaInformacion ci : CapaConsultas.getAllOrderedByOrden()) {
                if (ci.getOpcional() && ci.getHabilitada()) {
                    layers.add(new LayerElement(ci.getNombre(), ci.getUrl(), wasVisible(ci)));
                }
            }
            return null;
        }

        @Override
        protected void process(List<Object> chunks) {
            actualizando.setIcon(es.emergya.cliente.constants.LogicConstants.getIcon("anim_actualizando"));
        }

        @Override
        protected void done() {
            super.done();
            actualizando.setIcon(null);
            list.setLayout(new BoxLayout(list, BoxLayout.Y_AXIS));
            for (LayerElement le : layers) {
                JCheckBox cb = new JCheckBox(le.name, le.active);
                cb.setBackground(Color.WHITE);
                cb.addActionListener(LayerSelectionDialog.this);
                list.add(cb);
                list.revalidate();
            }

            // self.pack();
        }
    };
    sw.execute();
}

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

public void initialize() {
    final String workingId = PlatformUI.MIRTH_FRAME.startWorking("Loading library resources...");

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

        @Override/*w  w w .jav a2  s .c om*/
        public List<LibraryProperties> doInBackground() throws ClientException {
            List<ResourceProperties> resourceProperties = PlatformUI.MIRTH_FRAME.mirthClient.getResources();
            List<LibraryProperties> libraryProperties = new ArrayList<LibraryProperties>();
            for (ResourceProperties resource : resourceProperties) {
                if (resource instanceof LibraryProperties) {
                    libraryProperties.add((LibraryProperties) resource);
                }
            }
            return libraryProperties;
        }

        @Override
        public void done() {
            try {
                List<LibraryProperties> resources = get();
                if (resources == null) {
                    resources = new ArrayList<LibraryProperties>();
                }

                Object[][] data = new Object[resources.size()][3];
                int i = 0;

                for (LibraryProperties properties : resources) {
                    data[i][SELECTED_COLUMN] = null;
                    data[i][PROPERTIES_COLUMN] = properties;
                    data[i][TYPE_COLUMN] = properties.getType();
                    i++;

                    for (Map<String, String> resourceIds : selectedResourceIds.values()) {
                        if (resourceIds.containsKey(properties.getId())) {
                            resourceIds.put(properties.getId(), properties.getName());
                        }
                    }
                }

                ((RefreshTableModel) resourceTable.getModel()).refreshDataVector(data);

                treeTable.getSelectionModel().setSelectionInterval(0, 0);
                treeTable.getTreeSelectionModel().setSelectionPath(treeTable.getPathForRow(0));
                parent.resourcesReady();
            } catch (Throwable t) {
                if (t instanceof ExecutionException) {
                    t = t.getCause();
                }
                PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, t,
                        "Error loading library resources: " + t.toString());
            } finally {
                PlatformUI.MIRTH_FRAME.stopWorking(workingId);
            }
        }
    };

    worker.execute();
}

From source file:net.openbyte.gui.WorkFrame.java

private void menuItem1ActionPerformed(ActionEvent e) {
    if (this.api == ModificationAPI.BUKKIT) {
        showBukkitIncompatibleFeature();
        return;//from   ww  w . j  av a  2 s .  co  m
    }
    System.out.println("Starting client...");
    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() throws Exception {
            GradleConnector.newConnector().forProjectDirectory(workDirectory).connect().newBuild()
                    .forTasks("runClient").run();
            return null;
        }
    };
    if (this.api == ModificationAPI.MCP) {
        worker = new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() throws Exception {
                if (System.getProperty("os.name").startsWith("Windows")) {
                    Runtime.getRuntime().exec("cmd /c startclient.bat", null, workDirectory);
                    return null;
                }
                try {
                    CommandLine startClient = CommandLine.parse("python "
                            + new File(new File(workDirectory, "runtime"), "startclient.py").getAbsolutePath()
                            + " $@");
                    CommandLine authClient = CommandLine.parse("chmod 755 "
                            + new File(new File(workDirectory, "runtime"), "startclient.py").getAbsolutePath());
                    DefaultExecutor executor = new DefaultExecutor();
                    executor.setWorkingDirectory(workDirectory);
                    executor.execute(authClient);
                    executor.execute(startClient);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        };
    }
    worker.execute();
}

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

@Override
public void actionPerformed(final ActionEvent e) {

    final CustomMapView mapViewLocal = this.mapView;

    SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {
        @Override/*from www . ja  v a2 s  .  com*/
        protected Object doInBackground() throws Exception {

            try {
                final MouseEvent mouseEvent = FleetControlMapViewer.this.eventOriginal;
                if (e.getActionCommand().equals(// Centrar aqui
                        i18n.getString(Locale.ROOT, "map.menu.centerHere"))) {
                    mapViewLocal.zoomToFactor(mapViewLocal.getEastNorth(mouseEvent.getX(), mouseEvent.getY()),
                            mapViewLocal.zoomFactor);

                } else if (e.getActionCommand().equals(// nueva incidencia
                        i18n.getString("map.menu.newIncidence"))) {
                    Incidencia f = new Incidencia();
                    f.setCreador(Authentication.getUsuario());
                    LatLon from = mapViewLocal.getLatLon(mouseEvent.getX(), mouseEvent.getY());
                    GeometryFactory gf = new GeometryFactory();
                    f.setGeometria(gf.createPoint(new Coordinate(from.lon(), from.lat())));
                    IncidenceDialog id = new IncidenceDialog(f, i18n.getString("Incidences.summary.title") + " "
                            + i18n.getString("Incidences.nuevaIncidencia"), "tittleficha_icon_recurso");
                    id.setVisible(true);

                } else if (e.getActionCommand().equals(// ruta desde
                        i18n.getString("map.menu.route.from"))) {
                    routeDialog.showRouteDialog(mapViewLocal.getLatLon(mouseEvent.getX(), mouseEvent.getY()),
                            null, mapViewLocal);

                } else if (e.getActionCommand().equals(// ruta hasta
                        i18n.getString("map.menu.route.to"))) {
                    routeDialog.showRouteDialog(null,
                            mapViewLocal.getLatLon(mouseEvent.getX(), mouseEvent.getY()), mapViewLocal);

                } else if (e.getActionCommand().equals(// Actualizar gps
                        i18n.getString("map.menu.gps"))) {
                    if (!(menuObjective instanceof Recurso)) {
                        return null;
                    }

                    GPSDialog sdsDialog = null;
                    for (Frame f : Frame.getFrames()) {
                        if (f instanceof GPSDialog)
                            if (((GPSDialog) f).getRecurso().equals(menuObjective))
                                sdsDialog = (GPSDialog) f;
                    }
                    if (sdsDialog == null)
                        sdsDialog = new GPSDialog((Recurso) menuObjective);
                    sdsDialog.setVisible(true);
                    sdsDialog.setExtendedState(JFrame.NORMAL);

                } else if (e.getActionCommand().equals(// Ficha
                        i18n.getString("map.menu.summary"))) {
                    if (log.isTraceEnabled()) {
                        log.trace("Mostramos la ficha del objetivo del menu");
                    }
                    if (menuObjective instanceof Recurso) {
                        log.trace(">recurso");
                        SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {

                            @Override
                            protected Object doInBackground() throws Exception {
                                for (Frame f : JFrame.getFrames()) {
                                    if (f.getName().equals(((Recurso) menuObjective).getIdentificador())
                                            && f instanceof SummaryDialog) {
                                        if (f.isShowing()) {
                                            f.toFront();
                                            f.setExtendedState(JFrame.NORMAL);
                                            return null;
                                        }
                                    }
                                }
                                new SummaryDialog((Recurso) menuObjective).setVisible(true);
                                return null;
                            }
                        };

                        sw.execute();
                    } else if (menuObjective instanceof Incidencia) {
                        if (log.isTraceEnabled()) {
                            log.trace(">incidencia");
                        }
                        SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {

                            @Override
                            protected Object doInBackground() throws Exception {
                                for (Frame f : JFrame.getFrames()) {
                                    if (f.getName().equals(((Incidencia) menuObjective).getTitulo())
                                            && f instanceof IncidenceDialog) {
                                        if (log.isTraceEnabled()) {
                                            log.trace("Ya lo tenemos abierto");
                                        }
                                        if (f.isShowing()) {
                                            f.toFront();
                                            f.setExtendedState(JFrame.NORMAL);
                                        } else {
                                            f.setVisible(true);
                                            f.setExtendedState(JFrame.NORMAL);
                                        }
                                        return null;
                                    }
                                }
                                if (log.isTraceEnabled()) {
                                    log.trace("Abrimos uno nuevo");
                                }
                                new IncidenceDialog((Incidencia) menuObjective,
                                        i18n.getString("Incidences.summary.title") + " "
                                                + ((Incidencia) menuObjective).getTitulo(),
                                        "tittleficha_icon_recurso").setVisible(true);
                                return null;
                            }
                        };

                        sw.execute();
                    } else {
                        return null;
                    }

                } else if (e.getActionCommand().equals( // Mas cercanos
                        i18n.getString("map.menu.showNearest"))) {
                    if (log.isTraceEnabled()) {
                        log.trace("showNearest");
                    }

                    if (menuObjective != null) {
                        for (Frame f : JFrame.getFrames()) {
                            String identificador = menuObjective.toString();
                            if (menuObjective instanceof Recurso) {
                                identificador = ((Recurso) menuObjective).getIdentificador();
                            }
                            if (menuObjective != null && f.getName().equals(identificador)
                                    && f instanceof NearestResourcesDialog && f.isDisplayable()) {
                                if (log.isTraceEnabled()) {
                                    log.trace("Encontrado " + f);
                                }
                                if (f.isShowing()) {
                                    f.toFront();
                                    f.setExtendedState(JFrame.NORMAL);
                                } else {
                                    f.setVisible(true);
                                    f.setExtendedState(JFrame.NORMAL);
                                }
                                return null;
                            }
                        }
                    }
                    NearestResourcesDialog d;
                    if (menuObjective instanceof Recurso) {
                        d = new NearestResourcesDialog((Recurso) menuObjective, mapViewLocal);
                    } else if (menuObjective instanceof Incidencia) {
                        d = new NearestResourcesDialog((Incidencia) menuObjective,
                                mapViewLocal.getLatLon(mouseEvent.getX(), mouseEvent.getY()), mapViewLocal);
                    } else {
                        d = new NearestResourcesDialog(
                                mapViewLocal.getLatLon(mouseEvent.getX(), mouseEvent.getY()), mapViewLocal);
                    }
                    d.setVisible(true);

                } else {
                    log.error("ActionCommand desconocido: " + e.getActionCommand());
                }
            } catch (Throwable t) {
                log.error("Error al ejecutar la accion del menu contextual", t);
            }
            return null;
        }
    };

    sw.execute();
}

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

@Override
public void doRefresh() {
    if (PlatformUI.MIRTH_FRAME.alertRefresh()) {
        return;/*from   w  ww.  ja  v  a 2  s. co m*/
    }

    final String workingId = getFrame().startWorking("Loading resources...");
    final int selectedRow = resourceTable.getSelectedRow();

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

        @Override
        public List<ResourceProperties> doInBackground() throws ClientException {
            return getFrame().mirthClient.getResources();
        }

        @Override
        public void done() {
            try {
                updateResourcesTable(get(), selectedRow, true);
            } catch (Throwable t) {
                if (t instanceof ExecutionException) {
                    t = t.getCause();
                }
                getFrame().alertThrowable(getFrame(), t, "Error loading resources: " + t.toString());
            } finally {
                getFrame().stopWorking(workingId);
            }
        }
    };

    worker.execute();
}

From source file:com.demonwav.mcdev.creator.LiteLoaderProjectSettingsWizard.java

public LiteLoaderProjectSettingsWizard(@NotNull MinecraftProjectCreator creator) {
    this.creator = creator;

    mcpWarning.setVisible(false);// ww w .j  a  v a 2s  .  c o  m

    minecraftVersionBox.addActionListener(e -> {
        if (mcpVersion != null) {
            mcpVersion.setMcpVersion(mcpVersionBox, (String) minecraftVersionBox.getSelectedItem(),
                    mcpBoxActionListener);
        }
    });

    pluginNameField.getDocument().addDocumentListener(new DocumentAdapter() {
        @Override
        protected void textChanged(DocumentEvent e) {
            if (mainClassModified) {
                return;
            }

            String[] words = pluginNameField.getText().split("\\s+");
            String word = Arrays.stream(words).map(WordUtils::capitalize).collect(Collectors.joining());

            String[] mainClassWords = mainClassField.getText().split("\\.");
            mainClassWords[mainClassWords.length - 1] = LITEMOD + word;

            mainClassField.getDocument().removeDocumentListener(listener);
            mainClassField.setText(Arrays.stream(mainClassWords).collect(Collectors.joining(".")));
            mainClassField.getDocument().addDocumentListener(listener);
        }
    });

    mainClassField.getDocument().addDocumentListener(listener);

    try {
        new SwingWorker() {
            @Override
            protected Object doInBackground() throws Exception {
                mcpVersion = McpVersion.downloadData();
                return null;
            }

            @Override
            protected void done() {
                if (mcpVersion == null) {
                    return;
                }

                minecraftVersionBox.removeAllItems();

                mcpVersion.getVersions().forEach(minecraftVersionBox::addItem);
                // Always select most recent
                minecraftVersionBox.setSelectedIndex(0);

                if (mcpVersion != null) {
                    mcpVersion.setMcpVersion(mcpVersionBox, (String) minecraftVersionBox.getSelectedItem(),
                            mcpBoxActionListener);
                }

                loadingBar.setIndeterminate(false);
                loadingBar.setVisible(false);
            }
        }.execute();
    } catch (Exception e) {
        e.printStackTrace();
    }
}