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:net.openbyte.gui.WorkFrame.java

private void menuItem2ActionPerformed(ActionEvent e) {
    if (this.api == ModificationAPI.BUKKIT) {
        showBukkitIncompatibleFeature();
        return;//from  ww  w.  ja v a2  s.co  m
    }
    System.out.println("Starting server...");
    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() throws Exception {
            GradleConnector.newConnector().forProjectDirectory(workDirectory).connect().newBuild()
                    .forTasks("runServer").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 startserver.bat", null, workDirectory);
                    return null;
                }
                try {
                    CommandLine startServer = CommandLine.parse("python "
                            + new File(new File(workDirectory, "runtime"), "startserver.py").getAbsolutePath()
                            + " $@");
                    CommandLine authServer = CommandLine.parse("chmod 755 "
                            + new File(new File(workDirectory, "runtime"), "startserver.py").getAbsolutePath());
                    DefaultExecutor executor = new DefaultExecutor();
                    executor.setWorkingDirectory(workDirectory);
                    executor.execute(authServer);
                    executor.execute(startServer);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        };
    }
    worker.execute();
}

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

/**
 * // w ww  .  jav  a  2 s .com
 */
public void loadExactMatchAgents() {
    SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
        @Override
        protected Object doInBackground() throws Exception {
            buildAgentList();
            return null;
        }

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

From source file:be.ac.ua.comp.scarletnebula.gui.windows.GUI.java

public GUI() {
    chooseLookAndFeel();// w  w w . j  a va  2 s.co  m

    setTitle("Scarlet Nebula");
    setSize(700, 400);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    final ImageIcon icon = new ImageIcon(getClass().getResource("/images/icon48.png"));
    setIconImage(icon.getImage());

    addToolbar();

    final JPanel mainPanel = getMainPanel();

    add(mainPanel);

    addMenubar();
    setKeyboardAccelerators();

    setLocationRelativeTo(null);
    setLocationByPlatform(true);

    setVisible(true);

    // Last but not least, we construct a cloudmanager object, which will
    // cause it to load all providers and thus servers.
    // We also register ourselves as an observer for linking and unlinking
    // servers so we can update the serverlist.
    CloudManager.get().addServerLinkUnlinkObserver(this);

    (new SwingWorkerWithThrobber<Object, Object>(newThrobber("Loading servers...")) {

        @Override
        protected Object doInBackground() throws Exception {
            try {
                CloudManager.get().loadAllLinkedServers();

                // now start refreshing all servers if necessary
                for (final CloudProvider cloudprovider : CloudManager.get().getLinkedCloudProviders()) {
                    {

                        for (final Server server : cloudprovider.listLinkedServers()) {
                            if (server.getStatus() == VmState.PENDING) {
                                server.refreshUntilServerHasState(VmState.RUNNING);
                            }
                            if (server.getStatus() == VmState.REBOOTING) {
                                server.refreshUntilServerHasState(VmState.RUNNING);
                            }
                            if (server.getStatus() == VmState.STOPPING) {
                                server.refreshUntilServerHasState(VmState.TERMINATED);
                            }
                        }
                    }

                }
            } catch (final Exception e) {
                log.error("Error while getting servers", e);
            }
            return null;
        }

    }).execute();

    // If there are no linked cloudproviders, start the new provider wizard
    if (CloudManager.get().getLinkedCloudProviders().size() == 0) {
        final SwingWorker<Object, Object> welcomeWizardWorker = new SwingWorker<Object, Object>() {
            @Override
            protected Object doInBackground() throws Exception {
                new WelcomeWizard(GUI.this);
                return null;
            }
        };

        welcomeWizardWorker.execute();
    }
}

From source file:edu.ku.brc.specify.plugins.imgproc.ImageProcessorPanel.java

/**
 * //from   www.j a  va2 s  . c  om
 */
protected void doNextStep() {
    if (step > -1) {
        procObjs.get(step).setOn(false);
    }

    step++;
    if (step >= procObjs.size()) {
        step = 0;
    }

    System.out.println("Step: " + step);

    procObjs.get(step).setOn(true);

    SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {
        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#doInBackground()
         */
        @Override
        protected Integer doInBackground() throws Exception {
            switch (step) {
            case 0:
                acquireImages();
                break;

            case 1:
                processBarCode();
                break;

            case 2:
                processMetaData();
                break;

            case 3:
                processSaveToDisk();
                break;

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

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

public GPSDialog(Recurso r) {
    super();//from w  w w . j  a  v  a  2  s . c  om
    setAlwaysOnTop(true);
    setResizable(false);
    iconTransparente = LogicConstants.getIcon("48x48_transparente");
    iconEnviando = LogicConstants.getIcon("anim_actualizando");
    target = r;
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    setPreferredSize(new Dimension(400, 150));
    setTitle(i18n.getString("window.gps.titleBar") + " " + target.getIdentificador());
    try {
        setIconImage(((BasicWindow) GoClassLoader.getGoClassLoader().load(BasicWindow.class)).getFrame()
                .getIconImage());
    } catch (Throwable e) {
        LOG.error("There is no icon image", e);
    }

    JPanel base = new JPanel();

    base.setBackground(Color.WHITE);
    base.setLayout(new BoxLayout(base, BoxLayout.Y_AXIS));

    // Icono del titulo
    JPanel title = new JPanel(new FlowLayout(FlowLayout.LEADING));
    final JLabel titleLabel = new JLabel(i18n.getString("window.gps.title"),
            LogicConstants.getIcon("tittleventana_icon_actualizargps"), JLabel.LEFT);

    titleLabel.setFont(LogicConstants.deriveBoldFont(12f));
    title.add(titleLabel);
    title.setOpaque(false);
    base.add(title);

    // Area para mensajes
    JPanel notificationArea = new JPanel();

    notificationArea.setOpaque(false);
    notification = new JLabel("PLACEHOLDER");
    notification.setForeground(Color.WHITE);
    notificationArea.add(notification);
    base.add(notificationArea);

    JPanel buttons = new JPanel();

    buttons.setOpaque(false);
    buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
    actualizar = new JButton(i18n.getString("window.gps.button.actualizar"),
            LogicConstants.getIcon("ventanacontextual_button_solicitargps"));
    actualizar.addActionListener(this);
    buttons.add(actualizar);
    buttons.add(Box.createHorizontalGlue());
    progressIcon = new JLabel(iconTransparente);
    buttons.add(progressIcon);
    buttons.add(Box.createHorizontalGlue());

    JButton cancel = new JButton(i18n.getString("Buttons.cancel"), LogicConstants.getIcon("button_cancel"));

    cancel.addActionListener(this);
    buttons.add(cancel);
    base.add(buttons);
    getContentPane().add(base);
    pack();

    int x;
    int y;
    Container myParent;
    try {
        myParent = ((BasicWindow) GoClassLoader.getGoClassLoader().load(BasicWindow.class)).getFrame()
                .getContentPane();
        java.awt.Point topLeft = myParent.getLocationOnScreen();
        Dimension parentSize = myParent.getSize();

        Dimension mySize = getSize();

        if (parentSize.width > mySize.width)
            x = ((parentSize.width - mySize.width) / 2) + topLeft.x;
        else
            x = topLeft.x;

        if (parentSize.height > mySize.height)
            y = ((parentSize.height - mySize.height) / 2) + topLeft.y;
        else
            y = topLeft.y;

        setLocation(x, y);
    } catch (Throwable e1) {
        LOG.error("There is no basic window!", e1);
    }
    this.addWindowListener(new WindowAdapter() {
        @Override
        public void windowOpened(WindowEvent arg0) {
            deleteErrorMessage();
        }

        @Override
        public void windowClosed(WindowEvent arg0) {
            deleteErrorMessage();
        }

        @Override
        public void windowClosing(WindowEvent arg0) {
            deleteErrorMessage();
        }

        private void deleteErrorMessage() {
            SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {
                @Override
                protected Object doInBackground() throws Exception {
                    if (last_bandejaSalida != null) {
                        MessageGenerator.remove(last_bandejaSalida.getId());
                    }

                    return null;
                }

                @Override
                protected void done() {
                    super.done();
                    GPSDialog.this.progressIcon.setIcon(iconTransparente);
                    GPSDialog.this.progressIcon.repaint();
                    last_bandejaSalida = null;
                    GPSDialog.this.notification.setText("");
                    GPSDialog.this.notification.repaint();
                }
            };

            sw.execute();
        }
    });
}

From source file:com.diversityarrays.update.UpdateDialog.java

private void checkForUpdates(PrintStream ps) {

    StringBuilder sb = new StringBuilder(updateCheckRequest.updateBaseUrl);
    sb.append(updateCheckRequest.versionCode);
    if (RunMode.getRunMode().isDeveloper()) {
        sb.append("-dev"); //$NON-NLS-1$
    }/*from w  w w.jav a  2s . c o  m*/
    sb.append(".json"); //$NON-NLS-1$

    final String updateUrl;
    updateUrl = sb.toString();
    // updateUrl = "NONEXISTENT"; // Uncomment to check error

    final ProgressMonitor progressMonitor = new ProgressMonitor(updateCheckRequest.owner,
            Msg.PROGRESS_CHECKING(), null, 0, 0);

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

        @Override
        protected String doInBackground() throws Exception {

            // Thread.sleep(3000); // Uncomment to check delay

            BufferedReader reader = null;
            StringBuffer buffer = new StringBuffer();

            try {
                URL url = new URL(updateUrl);
                reader = new BufferedReader(new InputStreamReader(url.openStream()));
                int read;
                char[] chars = new char[1024];
                while ((read = reader.read(chars)) != -1) {
                    if (progressMonitor.isCanceled()) {
                        cancel(true);
                        return null;
                    }
                    buffer.append(chars, 0, read);
                }
            } catch (IOException e) {
                System.err.println("checkForUpdates: " + e.getMessage()); //$NON-NLS-1$
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }

            return buffer.toString();
        }

        @Override
        protected void done() {
            try {
                String json = get();
                Gson gson = new Gson();
                setKDXploreUpdate(gson.fromJson(json, KDXploreUpdate.class));
            } catch (CancellationException ignore) {
            } catch (InterruptedException ignore) {
            } catch (ExecutionException e) {
                Throwable cause = e.getCause();

                if (cause instanceof UnknownHostException) {
                    String site = extractSite(updateUrl);
                    ps.println(Msg.ERRMSG_UNABLE_TO_CONTACT_UPDATE_SITE(site));
                } else {
                    cause.printStackTrace(ps);
                }

                if (cause instanceof FileNotFoundException) {
                    FileNotFoundException fnf = (FileNotFoundException) cause;
                    if (updateUrl.equals(fnf.getMessage())) {
                        // Well maybe someone forgot to create the file on
                        // the server!
                        System.err.println("Maybe someone forgot to create the file!"); //$NON-NLS-1$
                        System.err.println(fnf.getMessage());

                        setKDXploreUpdate(new KDXploreUpdate(Msg.ERRMSG_PROBLEMS_CONTACTING_UPDATE_SERVER_1()));
                        return;
                    }
                }

                String msg = Msg.HTML_PROBLEMS_CONTACTING_UPDATE_2(StringUtil.htmlEscape(updateUrl),
                        cause.getClass().getSimpleName(), StringUtil.htmlEscape(cause.getMessage()));
                kdxploreUpdate = new KDXploreUpdate(msg);

                kdxploreUpdate.unknownHost = (cause instanceof UnknownHostException);
                return;
            }
        }

        private String extractSite(final String updateUrl) {
            String site = null;
            int spos = updateUrl.indexOf("://");
            if (spos > 0) {
                int epos = updateUrl.indexOf('/', spos + 1);
                if (epos > 0) {
                    site = updateUrl.substring(0, epos);
                }
            }
            if (site == null) {
                site = updateUrl;
            }
            return site;
        }
    };

    Closure<JDialog> onComplete = new Closure<JDialog>() {
        @Override
        public void execute(JDialog d) {
            if (!processReadUrlResult(updateUrl)) {
                d.dispose();
            } else {
                d.setVisible(true);
            }
        }
    };

    SwingWorkerCompletionWaiter waiter = new SwingWorkerCompletionWaiter(this, onComplete);
    worker.addPropertyChangeListener(waiter);

    worker.execute();
}

From source file:es.emergya.ui.base.plugins.PluginContainer.java

public void cleanUp() {
    SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {
        @Override//  w w w  . jav  a  2s .  c  o  m
        protected Object doInBackground() throws Exception {
            for (AbstractPlugin ap : PluginContainer.this.plugins)
                try {
                    if (ap instanceof CleanUp)
                        ((CleanUp) ap).cleanUp();
                } catch (Throwable t) {
                    log.error("Error on cleanUp " + ap, t);
                }

            for (DetachedTab t : window.getPluginContainer().getPane().getDetachedTabs())
                try {
                    t.dispose();
                } catch (Throwable e) {
                    log.error("Error on dispose " + t, e);
                }
            return null;
        }
    };

    sw.execute();
}

From source file:com.rubenlaguna.en4j.NoteContentViewModule.UnrecognizedResourceJPanel.java

private void jButton1MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseReleased
    new SwingWorker<Void, Void>() {

        @Override/*from  ww  w.j  a v a  2 s  .  c  o m*/
        protected Void doInBackground() throws Exception {
            try {
                //get temp dir
                //save resource to tmp file
                String extension = FilenameUtils.getExtension(resource.getFilename());
                File tempFile = File.createTempFile("en4j", "." + extension);
                tempFile.deleteOnExit();
                OutputStream os = new BufferedOutputStream(new FileOutputStream(tempFile));
                InputStream is = resource.getDataAsInputStream();
                // Transfer bytes from in to out
                byte[] buf = new byte[1024];
                int len;
                while ((len = is.read(buf)) > 0) {
                    os.write(buf, 0, len);
                }
                is.close();
                os.close();
                Desktop dt = Desktop.getDesktop();
                dt.open(tempFile);
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
            return null;
        }
    }.execute();
    // desktop api to open file

}

From source file:com.mirth.connect.plugins.datapruner.DataPrunerPanel.java

@Override
public boolean doSave() {
    if (!validateFields()) {
        return false;
    }//from w ww . j  a va 2  s. c  o m

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

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

        public Void doInBackground() {
            try {
                plugin.setPropertiesToServer(getProperties());
            } catch (Exception e) {
                getFrame().alertThrowable(getFrame(), e);
            }
            return null;
        }

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

    worker.execute();

    return true;
}

From source file:com.kenai.redminenb.issue.RedmineIssue.java

void opened() {
    if (Redmine.LOG.isLoggable(Level.FINE)) {
        Redmine.LOG.log(Level.FINE, "issue {0} open start", new Object[] { getID() });
    }//w  w w .  j  av  a  2 s.co m
    String refresh = System.getProperty("org.netbeans.modules.bugzilla.noIssueRefresh"); // NOI18N
    if (refresh != null && refresh.equals("true")) { // NOI18N
        return;
    }
    if (SwingUtilities.isEventDispatchThread()) {
        new SwingWorker<Object, Object>() {
            @Override
            protected Object doInBackground() throws Exception {
                refresh();
                return null;
            };
        }.execute();
    } else {
        refresh();
    }
    repository.scheduleForRefresh(getID());
    if (Redmine.LOG.isLoggable(Level.FINE)) {
        Redmine.LOG.log(Level.FINE, "issue {0} open finish", new Object[] { getID() });
    }
}