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:edu.ku.brc.af.core.SpecialMsgNotifier.java

public void checkForMessages() {
    if (blockMsg.get()) {
        return;/*from  ww  w. j  av  a2s . c  om*/
    }

    SwingWorker<Integer, Integer> msgCheckWorker = new SwingWorker<Integer, Integer>() {
        protected String msg = null;

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#doInBackground()
         */
        @Override
        protected Integer doInBackground() throws Exception {
            if (!blockMsg.get()) {
                try {
                    Thread.sleep(15000); // 15 seconds

                    String url = UIRegistry.getResourceString("CGI_BASE_URL") + "/getmsg2.php";
                    String installID = UsageTracker.getInstallId();

                    msg = send(url, installID);
                    msg = StringUtils.deleteWhitespace(msg);

                } catch (Exception ex) {
                    // die silently
                }
            }
            return null;
        }

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

            if (msg != null) {
                //System.out.println("["+msg+"]");

                if (StringUtils.isNotEmpty(msg) && !StringUtils.contains(msg, "NOMSG")) {
                    String header = msg.length() > 6 ? msg.substring(0, 7).toUpperCase() : "";
                    if (header.startsWith("<HTML>")) {
                        UIRegistry.showLocalizedError("NO_INTERNET");
                    } else {
                        UIRegistry.showError(JOptionPane.WARNING_MESSAGE, msg);
                    }
                }
            }

        }
    };

    msgCheckWorker.execute();
}

From source file:SplashScreenTest.java

/**
 * This method displays a frame with the same image as the splash screen.
 *//*from   w ww.  j  a  v a  2 s  . c o  m*/
private static void init2() {
    final Image img = Toolkit.getDefaultToolkit().getImage(splash.getImageURL());

    final JFrame splashFrame = new JFrame();
    splashFrame.setUndecorated(true);

    final JPanel splashPanel = new JPanel() {
        public void paintComponent(Graphics g) {
            g.drawImage(img, 0, 0, null);
        }
    };

    final JProgressBar progressBar = new JProgressBar();
    progressBar.setStringPainted(true);
    splashPanel.setLayout(new BorderLayout());
    splashPanel.add(progressBar, BorderLayout.SOUTH);

    splashFrame.add(splashPanel);
    splashFrame.setBounds(splash.getBounds());
    splashFrame.setVisible(true);

    new SwingWorker<Void, Integer>() {
        protected Void doInBackground() throws Exception {
            try {
                for (int i = 0; i <= 100; i++) {
                    publish(i);
                    Thread.sleep(100);
                }
            } catch (InterruptedException e) {
            }
            return null;
        }

        protected void process(List<Integer> chunks) {
            for (Integer chunk : chunks) {
                progressBar.setString("Loading module " + chunk);
                progressBar.setValue(chunk);
                splashPanel.repaint(); // because img is loaded asynchronously
            }
        }

        protected void done() {
            splashFrame.setVisible(false);

            JFrame frame = new JFrame();
            frame.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setTitle("SplashScreenTest");
            frame.setVisible(true);
        }
    }.execute();
}

From source file:de.atomfrede.tools.evalutation.evaluator.EvaluationController.java

public void startStandardEvaluation() {
    new SwingWorker<Void, Void>() {

        @Override/*w  ww.j  a  v a2 s  . c om*/
        protected Void doInBackground() throws Exception {
            disableButtons();
            setupStandardEvaluation();
            return null;
        }

        @Override
        protected void done() {
            enableButtons();
            mainPanel.removeProgressPanel();
        }
    }.execute();
}

From source file:interactivespaces.service.image.vision.opencv.swing.OpenCvMatPanel.java

/**
 * Draw an OpenCV image in the panel.//w w w  . j av  a2 s . c  o  m
 *
 * @param opencvImage
 *          the image to draw
 */
public void drawImage(final Mat opencvImage) {
    SwingWorker<BufferedImage, Void> worker = new SwingWorker<BufferedImage, Void>() {

        @Override
        protected BufferedImage doInBackground() throws Exception {
            return MatUtils.matToBufferedImage(opencvImage);
        }

        @Override
        protected void done() {
            try {
                image = get();

                repaint();

                if (releaseAfterDraw) {
                    opencvImage.release();
                }
            } catch (InterruptedException e) {
                log.info("Swing worker for rendering Mat images interrupted");
            } catch (ExecutionException e) {
                log.error("Error during Swing worker for rendering Mat images", e);
            }
        }
    };

    worker.execute();
}

From source file:net.sf.dvstar.transmission.dialogs.StatsDialog.java

/** Creates new form StatsDialog */
public StatsDialog(TransmissionView parent, TransmissionWebClient webClient, boolean modal) {
    super(parent.getFrame(), modal);
    this.webClient = webClient;
    this.parent = parent;
    initComponents();/*ww  w  . ja v  a 2  s  .  co  m*/
    int messageTimeout = 5000;

    new SwingWorker() {

        @Override
        protected Object doInBackground() throws Exception {
            fillData();
            return null;
        }
    }.execute();

    updaterTimer = new Timer(messageTimeout, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            new SwingWorker() {
                @Override
                protected Object doInBackground() throws Exception {
                    updaterTimer.stop();
                    fillData();
                    updaterTimer.start();
                    return null;
                }
            }.execute();
        }
    });

    updaterTimer.setRepeats(true);
    updaterTimer.start();
}

From source file:com.hccl.nlip.GUIMainPanel.java

private void episodeBtnActionPerformed(ActionEvent e) {
    syncParamsToControler();//from w ww.  jav a  2  s .  c o  m
    setEnableAllControl(false);
    new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() throws Exception {
            mazeEnv.doEpisodes(1, true);
            return null;
        }

        @Override
        protected void done() {
            setEnableAllControl(true);
            updateInfo();
        }
    }.execute();
}

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

@Override
public Component getTableCellEditorComponent(final JTable table, Object value, boolean isSelected,
        final int row, final int column) {
    JButton b = (JButton) value;
    b.setBorderPainted(false);//ww w .  ja v  a2s.com
    b.setContentAreaFilled(false);
    b.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {
                @Override
                protected Object doInBackground() throws Exception {
                    stopCellEditing();
                    return null;
                }
            };
            SwingUtilities.invokeLater(sw);

            SwingWorker<Object, Object> sw1 = new SwingWorker<Object, Object>() {
                @Override
                protected Object doInBackground() throws Exception {
                    table.repaint();
                    return null;
                }
            };
            SwingUtilities.invokeLater(sw1);
        }
    });
    return b;
}

From source file:com.mirth.connect.plugins.directoryresource.DirectoryResourcePropertiesPanel.java

@Override
public void setProperties(ResourceProperties properties) {
    final DirectoryResourceProperties props = (DirectoryResourceProperties) properties;
    directoryField.setText(props.getDirectory());
    includeSubdirectoriesCheckBox.setSelected(props.isDirectoryRecursion());
    descriptionTextPane.setText(props.getDescription());

    final String workingId = PlatformUI.MIRTH_FRAME.startWorking("Loading libraries...");

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

        @Override/*ww w .  j a va 2s. c  om*/
        public List<String> doInBackground() throws ClientException {
            return (List<String>) PlatformUI.MIRTH_FRAME.mirthClient
                    .getServlet(DirectoryResourceServletInterface.class).getLibraries(props.getId());
        }

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

                Object[][] data = new Object[libraries.size()][1];
                int i = 0;

                for (String library : libraries) {
                    data[i++][0] = library;
                }

                ((RefreshTableModel) libraryTable.getModel()).refreshDataVector(data);
            } catch (Throwable t) {
                if (t instanceof ExecutionException) {
                    t = t.getCause();
                }
                PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, t,
                        "Error loading libraries: " + t.toString());
            } finally {
                PlatformUI.MIRTH_FRAME.stopWorking(workingId);
            }
        }
    };

    worker.execute();
}

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

@Override
public void doRefresh() {
    final String workingId = getFrame().startWorking("Loading database tasks...");
    final int selectedRow = taskTable.getSelectedRow();

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

        @Override/*from www .  j ava2  s. co  m*/
        public Map<String, DatabaseTask> doInBackground() throws ClientException {
            return getFrame().mirthClient.getDatabaseTasks();
        }

        @Override
        public void done() {
            try {
                Map<String, DatabaseTask> databaseTasks = get();
                if (databaseTasks == null) {
                    databaseTasks = new HashMap<String, DatabaseTask>();
                }

                Object[][] data = new Object[databaseTasks.size()][4];
                int i = 0;

                for (DatabaseTask databaseTask : databaseTasks.values()) {
                    Status status = databaseTask.getStatus();
                    data[i][0] = new CellData(status == Status.IDLE ? UIConstants.ICON_BULLET_YELLOW
                            : UIConstants.ICON_BULLET_GREEN, status.toString());
                    data[i][1] = databaseTask;
                    data[i][2] = databaseTask.getDescription();
                    data[i][3] = databaseTask.getStartDateTime();
                    i++;
                }

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

                if (selectedRow > -1 && selectedRow < taskTable.getRowCount()) {
                    taskTable.setRowSelectionInterval(selectedRow, selectedRow);
                }
            } catch (Throwable t) {
                if (t instanceof ExecutionException) {
                    t = t.getCause();
                }
                getFrame().alertThrowable(getFrame(), t, "Error loading database tasks: " + t.toString());
            } finally {
                getFrame().stopWorking(workingId);
            }
        }
    };

    worker.execute();
}

From source file:edu.ku.brc.specify.plugins.sgr.HistogramChart.java

public HistogramChart(String name, Taskable task, BatchMatchResultSet resultSet,
        final SGRBatchScenario scenario, float binSize) {
    super(name, task);
    this.resultSet = resultSet;

    update();/*  w  w  w.  j a v  a2 s .  c  om*/

    chartUpdater = new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() throws Exception {
            Thread.currentThread().setName("Histogram-Updater");
            while (true) {
                try {
                    if (!scenario.isRunning())
                        return null;
                } catch (NullPointerException e) {
                    return null;
                }

                Thread.sleep(2000);
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        update();
                    }
                });
            }
        }
    };

    chartUpdater.execute();
}