Example usage for javax.swing SwingWorker addPropertyChangeListener

List of usage examples for javax.swing SwingWorker addPropertyChangeListener

Introduction

In this page you can find the example usage for javax.swing SwingWorker addPropertyChangeListener.

Prototype

public final void addPropertyChangeListener(PropertyChangeListener listener) 

Source Link

Document

Adds a PropertyChangeListener to the listener list.

Usage

From source file:Main.java

public static void main(String[] args) {
    JProgressBar progressBar = new JProgressBar();
    progressBar.setOpaque(false);//from  w w  w  .  j ava 2  s .c  o m
    progressBar.setUI(new GradientPalletProgressBarUI());

    JPanel p = new JPanel();
    p.add(progressBar);
    p.add(new JButton(new AbstractAction("Start") {
        @Override
        public void actionPerformed(ActionEvent e) {
            SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
                @Override
                public Void doInBackground() {
                    int current = 0, lengthOfTask = 100;
                    while (current <= lengthOfTask && !isCancelled()) {
                        try {
                            Thread.sleep(50);
                        } catch (Exception ie) {
                            return null;
                        }
                        setProgress(100 * current / lengthOfTask);
                        current++;
                    }
                    return null;
                }
            };
            worker.addPropertyChangeListener(new ProgressListener(progressBar));
            worker.execute();
        }
    }));

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.getContentPane().add(p);
    frame.setSize(320, 240);
    frame.setVisible(true);
}

From source file:com.anrisoftware.prefdialog.miscswing.docks.dockingframes.core.DockingFramesDock.java

private void doLoadLayout(String name, InputStream stream, PropertyChangeListener... listeners)
        throws LayoutInterruptedException, LayoutLoadingException {
    try {/*from  www. jav  a  2  s  .com*/
        SwingWorker<InputStream, InputStream> worker = loadFactory.create(layoutListeners, this, name, control,
                stream);
        for (PropertyChangeListener l : listeners) {
            worker.addPropertyChangeListener(l);
        }
        worker.execute();
        worker.get();
    } catch (InterruptedException e) {
        throw new LayoutInterruptedException(name, e);
    } catch (ExecutionException e) {
        throw new LayoutLoadingException(name, e.getCause());
    }
}

From source file:com.anrisoftware.prefdialog.miscswing.docks.dockingframes.core.DockingFramesDock.java

private void doSaveLayout(String name, OutputStream stream, PropertyChangeListener... listeners)
        throws LayoutException {
    try {//from www  .ja v  a  2 s . c  om
        SwingWorker<OutputStream, OutputStream> worker = saveFactory.create(layoutListeners, this, name,
                control, stream);
        for (PropertyChangeListener l : listeners) {
            worker.addPropertyChangeListener(l);
        }
        worker.execute();
        worker.get();
    } catch (ExecutionException e) {
        throw new LayoutSavingException(name, e.getCause());
    } catch (InterruptedException e) {
        throw new LayoutInterruptedException(name, e);
    }

}

From source file:com.dfki.av.sudplan.ui.MainFrame.java

private void bGoWMSHeightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bGoWMSHeightActionPerformed
    String urlString;/*from  w w w  . j  av a  2  s  . c om*/
    if (rbCbServerUrl.isSelected()) {
        urlString = cbServerURL.getSelectedItem().toString();
    } else {
        urlString = txtServerURL.getText();
    }
    bGoWMSHeight.setEnabled(false);
    pbWMS.setIndeterminate(true);
    pbWMS.setVisible(true);
    SwingWorker worker = new LayerInfoRetreiver(urlString, false);
    worker.addPropertyChangeListener(this);
    worker.execute();
}

From source file:de.tntinteractive.portalsammler.gui.MainDialog.java

private void poll(final Gui gui) {

    this.pollButton.setEnabled(false);

    final Settings settings = this.getStore().getSettings().deepClone();
    final ProgressMonitor progress = new ProgressMonitor(this, "Sammle Daten aus den Quell-Portalen...", "...",
            0, settings.getSize());//ww w. j a  v a 2  s  .com
    progress.setMillisToDecideToPopup(0);
    progress.setMillisToPopup(0);
    progress.setProgress(0);

    final SwingWorker<String, String> task = new SwingWorker<String, String>() {

        @Override
        protected String doInBackground() throws Exception {
            final StringBuilder summary = new StringBuilder();
            int cnt = 0;
            for (final String id : settings.getAllSettingIds()) {
                if (this.isCancelled()) {
                    break;
                }
                cnt++;
                this.publish(cnt + ": " + id);
                final Pair<Integer, Integer> counts = MainDialog.this.pollSingleSource(settings, id);
                summary.append(id).append(": ");
                if (counts != null) {
                    summary.append(counts.getLeft()).append(" neu, ").append(counts.getRight())
                            .append(" schon bekannt\n");
                } else {
                    summary.append("Fehler!\n");
                }
                this.setProgress(cnt);
            }
            MainDialog.this.getStore().writeMetadata();
            return summary.toString();
        }

        @Override
        protected void process(final List<String> ids) {
            progress.setNote(ids.get(ids.size() - 1));
        }

        @Override
        public void done() {
            MainDialog.this.pollButton.setEnabled(true);
            MainDialog.this.table.refreshContents();
            try {
                final String summary = this.get();
                JOptionPane.showMessageDialog(MainDialog.this, summary, "Abruf-Zusammenfassung",
                        JOptionPane.INFORMATION_MESSAGE);
            } catch (final Exception e) {
                gui.showError(e);
            }
        }

    };

    task.addPropertyChangeListener(new PropertyChangeListener() {
        @Override
        public void propertyChange(final PropertyChangeEvent evt) {
            if ("progress".equals(evt.getPropertyName())) {
                progress.setProgress((Integer) evt.getNewValue());
            }
            if (progress.isCanceled()) {
                task.cancel(true);
            }
        }
    });

    task.execute();
}

From source file:org.usfirst.frc.team2084.neuralnetwork.HeadingNeuralNetworkTrainer.java

private void trainNetwork() {
    if (!training) {

        // Set training flag and disable button
        training = true;//from  ww  w.  jav a  2  s. c om
        trainButton.setEnabled(false);

        final ProgressMonitor progressMonitor = new ProgressMonitor(frame, "Training Network...", "", 0, 100);
        progressMonitor.setMillisToDecideToPopup(100);
        progressMonitor.setMillisToPopup(400);

        @SuppressWarnings("unchecked")
        final ArrayList<XYDataItem> data = new ArrayList<>(outputGraphDataSeries.getItems());

        final int maxProgress = iterations * data.size();

        final SwingWorker<Void, Void> trainingWorker = new SwingWorker<Void, Void>() {

            @Override
            protected Void doInBackground() throws Exception {
                // Reset the neural network to default values
                synchronized (this) {
                    network.reset();
                    network.setEta(eta);
                    network.setMomentum(momentum);
                }

                outer: for (int j = 0; j < iterations; j++) {
                    for (int i = 0; i < data.size(); i++) {
                        if (!isCancelled()) {
                            XYDataItem d = data.get(i);
                            double error = convertAngleToInput(d.getXValue());
                            double output = d.getYValue();
                            synchronized (this) {
                                network.feedForward(error);
                                network.backPropagation(output);
                            }
                            int jl = j;
                            int il = i;
                            int progress = (int) (((float) (data.size() * jl + il + 1) / maxProgress) * 100);
                            setProgress(progress);
                        } else {
                            break outer;
                        }
                    }
                }

                displayNetwork();
                return null;
            }

            @Override
            protected void done() {
                training = false;
                trainButton.setEnabled(true);
                progressMonitor.close();
            }
        };
        trainingWorker.addPropertyChangeListener(new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("progress")) {
                    progressMonitor.setProgress((int) evt.getNewValue());
                }
                if (progressMonitor.isCanceled()) {
                    trainingWorker.cancel(true);
                }
            }
        });
        trainingWorker.execute();
    }
}

From source file:edu.ku.brc.specify.tools.l10nios.StrLocalizerAppForiOS.java

private void scanSources() {
    scanMI.setEnabled(false);//from   w  ww  .ja va 2  s . co m

    final String STATUSBAR_NAME = "STATUS";
    final JStatusBar statusBar = UIRegistry.getStatusBar();
    statusBar.setProgressRange(STATUSBAR_NAME, 0, 100);

    SwingWorker<Integer, Integer> translator = new SwingWorker<Integer, Integer>() {
        @Override
        protected Integer doInBackground() throws Exception {
            doScanSources();
            return null;
        }

        @Override
        protected void done() {
            scanMI.setEnabled(false);
        }
    };

    translator.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if ("progress".equals(evt.getPropertyName())) {
                statusBar.setText(String.format("%d / 100 ", (Integer) evt.getNewValue()) + "%");
            }
        }
    });
    translator.execute();
}

From source file:edu.ku.brc.specify.dbsupport.SpecifyDeleteHelper.java

/**
 * @param workerArg//from   w w w  . j av  a 2s.com
 * @param title (already localized)
 * @return a modal dialog showing the progress
 */
public JDialog initProgress(final SwingWorker<?, ?> workerArg, final String title) {
    this.worker = workerArg;

    if (workerArg != null) {
        JDialog dialog = new JDialog((Dialog) null, true);

        titleLbl = new JLabel(title);
        progressBar = new JProgressBar(0, 100);

        CellConstraints cc = new CellConstraints();
        PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "f:p:g,p,4px,p,f:p:g"));

        pb.add(titleLbl, cc.xy(1, 2));
        pb.add(progressBar, cc.xy(1, 4));
        pb.setDefaultDialogBorder();
        dialog.setContentPane(pb.getPanel());

        dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        dialog.pack();
        dialog.setSize(500, 150);
        workerArg.addPropertyChangeListener(new SwingWorkerCompletionWaiter(dialog));
        return dialog;
    }
    return null;
}

From source file:edu.ku.brc.specify.tools.schemalocale.SchemaToolsDlg.java

/**
 * // w  w  w .ja v  a2s . c  o  m
 */
private void importSchema(final boolean doLocalization) {
    FileDialog fileDlg = new FileDialog((Dialog) null);
    fileDlg.setTitle(getResourceString(doLocalization ? SL_CHS_LOC : SL_CHS_IMP));
    UIHelper.centerAndShow(fileDlg);

    String fileName = fileDlg.getFile();
    if (StringUtils.isNotEmpty(fileName)) {
        String title = getResourceString(doLocalization ? "SL_L10N_SCHEMA" : "SL_IMPORT_SCHEMA");

        final File file = new File(fileDlg.getDirectory() + File.separator + fileName);
        final SimpleGlassPane glassPane = new SimpleGlassPane(title, 18);
        glassPane.setBarHeight(12);
        glassPane.setFillColor(new Color(0, 0, 0, 85));

        setGlassPane(glassPane);
        glassPane.setVisible(true);

        SwingWorker<Integer, Integer> importWorker = new SwingWorker<Integer, Integer>() {
            private boolean isOK = false;

            @Override
            protected Integer doInBackground() throws Exception {
                DataProviderSessionIFace localSession = null;
                try {
                    localSession = DataProviderFactory.getInstance().createSession();

                    localSession.beginTransaction();

                    BuildSampleDatabase bsd = new BuildSampleDatabase();

                    Discipline discipline = localSession.get(Discipline.class,
                            AppContextMgr.getInstance().getClassObject(Discipline.class).getId());

                    isOK = bsd.loadSchemaLocalization(discipline, schemaType, DBTableIdMgr.getInstance(), null, //catFmtName,
                            null, //accFmtName,
                            doLocalization ? UpdateType.eLocalize : UpdateType.eImport, // isDoingUpdate
                            file, // external file
                            glassPane, localSession);
                    if (isOK) {
                        localSession.commit();
                    } else {
                        localSession.rollback();
                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BuildSampleDatabase.class, ex);

                } finally {
                    if (localSession != null) {
                        localSession.close();
                    }
                }

                return null;
            }

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

                glassPane.setVisible(false);

                if (isOK) {
                    UIRegistry.showLocalizedMsg("Specify.ABT_EXIT");
                    CommandDispatcher.dispatch(new CommandAction("App", "AppReqExit"));
                }
            }
        };
        importWorker.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(final PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("progress")) {
                    glassPane.setProgress((Integer) evt.getNewValue());
                }
            }
        });
        importWorker.execute();
    }
}

From source file:edu.ku.brc.specify.tasks.CleanupToolsTask.java

/**
 * //from  w ww . ja v  a 2 s  .c om
 */
private void updateNames(final Vector<AgentNameCleanupParserDlg.DataItem> dataItemsList) {
    final String PRC = "PROCESS";
    final SimpleGlassPane glassPane = UIRegistry.writeSimpleGlassPaneMsg("Processing agents...", 24);

    //prgDlg = new ProgressDialog(getResourceString("CLNUP_AG_PRG_TITLE"), true, false);
    //prgDlg.getProcessProgress().setIndeterminate(true);
    //prgDlg.setDesc(getResourceString("CLNUP_AG_INIT_MSG"));
    //UIHelper.centerAndShow(prgDlg);

    final SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
        double tot = 0; // 1 -> 100
        double step = 1.0;
        int cnt = 0;

        @Override
        protected Object doInBackground() throws Exception {
            step = 100.0 / dataItemsList.size();

            Connection conn = null;
            PreparedStatement pStmt = null;
            try {
                String sql = "UPDATE agent SET LastName=?, FirstName=?,MiddleInitial=? WHERE AgentID = ?";
                conn = DBConnection.getInstance().createConnection();
                pStmt = conn.prepareStatement(sql);

                for (DataItem di : dataItemsList) {
                    if (di.isIncluded()) {
                        setColumn(pStmt, 1, di.getLastName());
                        setColumn(pStmt, 2, di.getFirstName());
                        setColumn(pStmt, 3, di.getMidName());
                        pStmt.setInt(4, di.getAgentId());

                        if (pStmt.executeUpdate() != 1) {
                            log.error(String.format("Error updating AgentID %d", di.getAgentId()));
                        }
                    }

                    tot += step;
                    if (((int) tot) > cnt) {
                        cnt = (int) tot;
                        firePropertyChange(PRC, -1, cnt);
                    }
                }
                dataItemsList.clear();

            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    if (pStmt != null)
                        pStmt.close();
                    if (conn != null)
                        conn.close();

                } catch (SQLException ex) {
                }
            }
            return null;
        }

        @Override
        protected void done() {
            UIRegistry.clearSimpleGlassPaneMsg();
            UIRegistry.showLocalizedMsg("Done.");
        }
    };
    worker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            if (PRC.equals(evt.getPropertyName())) {
                glassPane.setProgress((Integer) evt.getNewValue());
            }
        }
    });
    worker.execute();
}