コード例 #1
0
  public void start(boolean return_when_done) {
    // TODO Auto-generated method stub
    SwingWorker worker =
        new SwingWorker() {

          final NodeDistances this$0;

          protected Object doInBackground() throws Exception {
            return new NodeDistancesTask();
          }

          {
            this$0 = NodeDistances.this;
            // super();
          }
        };
    worker.execute();
    if (return_when_done)
      try {
        worker.get();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (ExecutionException e) {
        e.printStackTrace();
      }
  }
コード例 #2
0
ファイル: CustomMapView.java プロジェクト: juanje/gofleet
  /** Updates all the markers in marker layers */
  public void updateMarkers() {
    Rectangle r = getBoundingBox();
    final LatLon tl, br;
    // tomamos los pois en un area de 3 pantallas cuadradas, de manera que
    // se pueda arrastrar sin notar que no estan cargados los poi de mas
    // allá, ya que solo se deberian cargar cuando deja de moverse.
    tl = getLatLon(r.x - r.width, r.y - r.height);
    br = getLatLon(r.x + 2 * r.width, r.y + 2 * r.height);

    if (mapUpdater == null || mapUpdater.isDone()) {
      mapUpdater =
          new SwingWorker<Object, Object>() {

            @Override
            protected Object doInBackground() throws Exception {
              try {
                updateIncidences(tl, br);
                updateResources(tl, br);
              } catch (Throwable t) {
                log.error("Error al actualizar marcadores", t);
              }
              return null;
            }

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

      mapUpdater.execute();
    }
  }
コード例 #3
0
ファイル: ExpeditionJasper.java プロジェクト: wibawamw/GARIS
  @Override
  public synchronized JasperReport loadReportFile() {
    try {
      SwingWorker<JasperReport, Void> worker =
          new SwingWorker<JasperReport, Void>() {

            @Override
            protected JasperReport doInBackground() throws Exception {
              try {
                String filename = "Expedition.jrxml";
                jasperReport = JasperCompileManager.compileReport("printing/" + filename);
              } catch (Exception ex) {
                Exceptions.printStackTrace(ex);
              }
              return jasperReport;
            }
          };
      worker.execute();
      jasperReport = worker.get();
    } catch (InterruptedException ex) {
      Exceptions.printStackTrace(ex);
    } catch (ExecutionException ex) {
      Exceptions.printStackTrace(ex);
    }
    return jasperReport;
  }
コード例 #4
0
  private void requestAccessToken() {
    if (loginModel.isServerSelected()) {
      SwingWorker<String, Object> worker =
          new SwingWorker<String, Object>() {

            @Override
            protected String doInBackground() throws Exception {
              if (!requestRunning) {
                requestRunning = true;
                boolean success = (loginModel.getAccessToken() == ResponseCode.SUCCESS);
                if (!success) {
                  errorLabel.setText(getLocalized(APP_NOT_AUTHORIZED_IN_STUDIP_LABEL));
                } else {
                  errorLabel.setText("");
                  model
                      .getPluginModel()
                      .activateNewPlugin(
                          loginModel.getPluginInformation(), loginModel.getOAuthConnector());
                }
              }
              return "done";
            }
          };
      errorLabel.setText("");
      setBussyMouse(true);
      worker.execute();
    }
  }
コード例 #5
0
  /*Called when the panel is set. Real istallation will start from here */
  @Override
  public void display() {
    progressBar.setIndeterminate(true);

    // now start the real installation!!
    final BatchInstaller batch =
        new BatchInstaller(
            WizardSettingsContainer.getInstance().getDbInfos(),
            WizardSettingsContainer.getInstance().getInstallDirectoryPath(),
            progressBar,
            progressString,
            WizardSettingsContainer.getInstance().isInitDB(),
            WizardSettingsContainer.getInstance().isInstallDesigner());

    // Execute installation task in background: GUI is still responsive :)
    SwingWorker<String, Object> worker =
        new SwingWorker() {
          public String doInBackground() {
            batch.doInstall();
            ActualInstallationWizardPanel.this.remove(progressBar);
            waitLabel.setText("Installation Completed");
            reallyFinisehd = true;
            ActualInstallationWizardPanel.this.repaint();
            return "finished";
          }

          protected void done() {
            progressBar.setEnabled(false);
          }
        };
    worker.execute();
  }
コード例 #6
0
  public void updateGUI() {
    SwingWorker<AnimationPanel, Void> swingWorker;
    swingWorker =
        new SwingWorker<AnimationPanel, Void>() {

          @Override
          protected AnimationPanel doInBackground() throws Exception {
            return ControlCenter.animationPanel;
          }

          @Override
          protected void done() {
            try {
              ControlCenterServices.time_step++;
              AnimationPanel panel = get();
              panel.clearUAVImageBeforeUpdate();
              panel.updateImageAtEachIteration();
              panel.repaint();
            } catch (InterruptedException | ExecutionException e) {

            }
          }
        };
    swingWorker.execute();
  }
コード例 #7
0
  private void orphanedSKUsFixActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_orphanedSKUsFixActionPerformed
    SwingWorker<Void, Void> worker =
        new SwingWorker<Void, Void>() {
          @Override
          protected Void doInBackground() throws Exception {
            orphanedSKUsFix.setEnabled(false);
            percentage = 0;
            int counter = 0;
            long starttimer;
            long timerSeconds;
            newThread = new Thread(new ProgressThread(orphanedSKUsProgress, true));
            apiLimitThread = new Thread(new UpdateThread(desktop.getConnectivity()));
            apiLimitThread.start();
            newThread.start();
            currentTask = "Deleting SKUs";
            Statement retrieveData = database.createStatement();
            retrieveData.setQueryTimeout(30);
            try {
              ResultSet orphanedSKUs =
                  retrieveData.executeQuery(
                      "SELECT skuid "
                          + "FROM allSKUs AS child "
                          + "WHERE NOT EXISTS "
                          + "(SELECT 1 FROM allProducts AS parent "
                          + "WHERE parent.prodid = child.prodid);");

              while (orphanedSKUs.next()) {
                starttimer = System.nanoTime();
                store.delete("products/skus/" + orphanedSKUs.getInt("skuid"));
                counter++;
                percentage = (counter * 100) / orphanedSkus;
                timerSeconds = (System.nanoTime() - starttimer) * (orphanedSkus - counter);
                timer = "";
                int day = (int) TimeUnit.NANOSECONDS.toDays(timerSeconds);
                long hours = TimeUnit.NANOSECONDS.toHours(timerSeconds) - (day * 24);
                long minute =
                    TimeUnit.NANOSECONDS.toMinutes(timerSeconds)
                        - (TimeUnit.NANOSECONDS.toHours(timerSeconds) * 60);
                long second =
                    TimeUnit.NANOSECONDS.toSeconds(timerSeconds)
                        - (TimeUnit.NANOSECONDS.toMinutes(timerSeconds) * 60);
                if (day > 0) timer += day + "d ";
                if (hours > 0) timer += hours + "h ";
                if (minute > 0) timer += minute + "m ";
                if (second > 0) timer += second + "s ";
              }
            } catch (SQLException ex) {
              System.out.println("Issue with the following: " + ex.getMessage());
            }
            retrieveData.close();
            return null;
          }
        };
    worker.execute();
  } // GEN-LAST:event_orphanedSKUsFixActionPerformed
コード例 #8
0
  /** パースした検査結果を登録する。 */
  private void addLabtest() {

    final List<NLaboImportSummary> modules = getTableModel().getDataProvider();

    final javax.swing.SwingWorker worker =
        new javax.swing.SwingWorker<Void, Void>() {

          @Override
          protected Void doInBackground() throws Exception {

            LaboDelegater laboDelegater = new LaboDelegater();

            for (NLaboImportSummary summary : modules) {

              PatientModel pm = laboDelegater.putNLaboModule(summary.getModule());

              if (pm != null) {
                summary.setPatient(pm);
                summary.setResult(SUCCESS);

              } else {
                summary.setResult(ERROR);
              }

              // Table 更新
              Runnable awt =
                  new Runnable() {
                    @Override
                    public void run() {
                      getTableModel().fireTableDataChanged();
                    }
                  };
              EventQueue.invokeLater(awt);
            }

            return null;
          }
        };

    worker.addPropertyChangeListener(
        new PropertyChangeListener() {

          @Override
          public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getNewValue().equals(javax.swing.SwingWorker.StateValue.STARTED)) {
              getProgressBar().setIndeterminate(true);
            } else if (evt.getNewValue().equals(javax.swing.SwingWorker.StateValue.DONE)) {
              getProgressBar().setIndeterminate(false);
              getProgressBar().setValue(0);
              worker.removePropertyChangeListener(this);
            }
          }
        });

    worker.execute();
  }
コード例 #9
0
  public static void saveManySplashImages() {
    boolean okPressed = SingleDirChooserPanel.selectOutputDir(true);
    if (!okPressed) {
      return;
    }

    ProgressMonitor progressMonitor =
        Utils.createPercentageProgressMonitor("Save Many Splash Images", "Stop");

    SwingWorker<Void, Void> worker =
        new SwingWorker<Void, Void>() {
          @Override
          public Void doInBackground() {
            int nurOfSplashImages = 32;

            for (int i = 0; i < nurOfSplashImages; i++) {
              OutputFormat outputFormat = OutputFormat.getLastOutputFormat();

              String fileName = String.format("splash%04d.%s", i, outputFormat.toString());

              progressMonitor.setProgress((int) ((float) i * 100 / nurOfSplashImages));
              progressMonitor.setNote("Creating " + fileName);
              if (progressMonitor.isCanceled()) {
                break;
              }

              Runnable guiTask =
                  () -> {
                    createSplashImage();

                    File lastSaveDir = FileChoosers.getLastSaveDir();
                    File f = new File(lastSaveDir, fileName);

                    Composition comp = ImageComponents.getActiveComp().get();

                    outputFormat.saveComposition(comp, f, false);

                    ImageComponents.getActiveIC().close();
                    ValueNoise.reseed();
                  };
              try {
                EventQueue.invokeAndWait(guiTask);
                Thread.sleep(1000L);
              } catch (InterruptedException | InvocationTargetException e) {
                Messages.showException(e);
              }
            } // end of for loop
            progressMonitor.close();
            return null;
          } // end of doInBackground()
        };
    worker.execute();
  }
コード例 #10
0
  @Override
  public void performAction() {
    Properties config = new Properties();
    config.setProperty(
        IComputeQuality.class.getSimpleName(),
        "it.unibas.spicy.findmappings.strategies.computequality.ComputeQualityStructuralAnalysis");
    Application.reset(config);
    executeInjection();
    mappingFinder.cleanUp();
    Scenario scenario = (Scenario) modello.getBean(Costanti.CURRENT_SCENARIO);
    MappingTask mappingTask = scenario.getMappingTask();
    if (mappingTask.getTargetProxy().getInstances().isEmpty()) {
      NotifyDescriptor nd =
          new NotifyDescriptor.Message(
              NbBundle.getMessage(Costanti.class, Costanti.WARNING_NOT_TARGET_INSTANCES),
              DialogDescriptor.WARNING_MESSAGE);
      DialogDisplayer.getDefault().notify(nd);
      return;
    }
    checkValueCorrespondenceInMappingTask(mappingTask);
    SwingWorker swingWorker =
        new SwingWorker() {

          private Scenario scenario;

          @Override
          protected Object doInBackground() throws Exception {
            scenario = (Scenario) modello.getBean(Costanti.CURRENT_SCENARIO);
            MappingTask mappingTask = scenario.getMappingTask();

            List<AnnotatedMappingTask> bestMappingTasks =
                mappingFinder.findBestMappings(mappingTask);
            modello.putBean(Costanti.BEST_MAPPING_TASKS, bestMappingTasks);
            IOProvider.getDefault().getIO(Costanti.FLUSSO_SPICY, false).select();
            return true;
          }

          @Override
          protected void done() {
            try {
              if ((Boolean) get() && !isCancelled()) {
                actionViewSpicy.performActionWithScenario(this.scenario);
                actionViewBestMappings.performActionWithScenario(this.scenario);
              }
            } catch (InterruptedException ex) {
              logger.error(ex);
            } catch (ExecutionException ex) {
              logger.error(ex);
            }
          }
        };
    swingWorker.execute();
  }
コード例 #11
0
  /*
   * (non-Javadoc)
   *
   * @see com.intel.stl.ui.email.IEmailControl#onTest()
   */
  @Override
  public void onTest() {
    view.showTesting(true);
    SwingWorker<Void, Void> worker =
        new SwingWorker<Void, Void>() {

          /*
           * (non-Javadoc)
           *
           * @see javax.swing.SwingWorker#doInBackground()
           */
          @Override
          protected Void doInBackground() throws Exception {
            // Should retrieve the values presently set in the view and use
            // these values to send the test email
            String testSmtpHostName = view.getSmtpServerNameStr();
            String testSmtpPortNum = view.getSmtpServerPortStr();
            String testToAddr = view.getToAddrStr();
            String testFromAddr = view.getFromAddrStr();

            // Test connection with above values...
            MailProperties mailProperties = new MailProperties();
            mailProperties.setSmtpServer(testSmtpHostName);
            mailProperties.setFromAddr(testFromAddr);
            mailProperties.setSmtpPort(new Integer(testSmtpPortNum));
            String subject = UILabels.STL92001_TEST_EMAIL_SUBJECT.getDescription();
            String body = "";
            subnetMgr.getConfigurationApi().sendTestMail(mailProperties, testToAddr, subject, body);
            return null;
          }

          /*
           * (non-Javadoc)
           *
           * @see javax.swing.SwingWorker#done()
           */
          @Override
          protected void done() {
            try {
              get();
            } catch (InterruptedException e) {
            } catch (ExecutionException e) {
              Util.showError(view, e);
            } finally {
              view.showTesting(false);
            }
          }
        };
    worker.execute();
  }
コード例 #12
0
  public boolean start() {
    makeBusy(true);

    worker = new SwingWorkerImpl();
    worker.addPropertyChangeListener(
        new PropertyChangeListener() {
          @Override
          public void propertyChange(PropertyChangeEvent evt) {
            firePropertyChange(STATE_PROPERTY, null, worker.getState());
          }
        });
    worker.execute();
    return true;
  }
コード例 #13
0
ファイル: SwingEngine.java プロジェクト: cinquin/pathvisio
 // TODO: deprecate
 public boolean processTask(
     ProgressKeeper pk, ProgressDialog d, SwingWorker<Boolean, Boolean> sw) {
   sw.execute();
   d.setVisible(true);
   try {
     return sw.get();
   } catch (ExecutionException e) {
     handleConverterException("Exception during conversion", null, e.getCause());
     return false;
   } catch (InterruptedException e) {
     handleConverterException("Conversion was cancelled or interrupted", null, e);
     return false;
   }
 }
コード例 #14
0
ファイル: DBSettings.java プロジェクト: souley/plier-toolbox
 void showProgressMonitor() {
   progressMonitor =
       new ProgressMonitor(DBSettings.this, "Building internal data ...", "", 0, 100);
   progressMonitor.setProgress(0);
   if (dbURL.matches("(?i:.*oracle.*)")) {
     task = QueryManager.instance().initFinder(QueryManager.SearchEngine.ORACLE, this);
   }
   if (dbURL.matches("(?i:.*mysql.*)")) {
     task = QueryManager.instance().initFinder(QueryManager.SearchEngine.MYSQL, this);
   }
   if (task != null) {
     task.addPropertyChangeListener(this);
     task.execute();
   }
 }
コード例 #15
0
ファイル: ContentUtils.java プロジェクト: sleuthkit/autopsy
    public Void visitDir(AbstractFile dir) {

      // don't extract . and .. directories
      if (isDotDirectory(dir)) {
        return null;
      }

      dest.mkdir();

      try {
        int numProcessed = 0;
        // recurse on children
        for (Content child : dir.getChildren()) {
          java.io.File childFile = getFsContentDest(child);
          ExtractFscContentVisitor<T, V> childVisitor =
              new ExtractFscContentVisitor<>(childFile, progress, worker, false);
          // If this is the source directory of an extract it
          // will have a progress and worker, and will keep track
          // of the progress bar's progress
          if (worker != null && worker.isCancelled()) {
            break;
          }
          if (progress != null && source) {
            progress.progress(child.getName(), numProcessed);
          }
          child.accept(childVisitor);
          numProcessed++;
        }
      } catch (TskException ex) {
        logger.log(Level.SEVERE, "Trouble fetching children to extract.", ex); // NON-NLS
      }

      return null;
    }
コード例 #16
0
ファイル: IngestManager.java プロジェクト: raman-bt/autopsy
    /* clean up or start the worker threads */
    @Override
    protected void done() {
      try {
        super.get(); // block and get all exceptions thrown while doInBackground()
      } catch (CancellationException e) {
        // task was cancelled
        handleInterruption(e);
      } catch (InterruptedException ex) {
        handleInterruption(ex);
      } catch (ExecutionException ex) {
        handleInterruption(ex);

      } catch (Exception ex) {
        handleInterruption(ex);

      } finally {
        // queing end
        if (this.isCancelled()) {
          // empty queues
          handleInterruption(new Exception());
        } else {
          // start ingest workers
          startAll();
        }
        progress.finish();
      }
    }
コード例 #17
0
  private void printButtonActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_printButtonActionPerformed
    final SwingWorker<Void, Void> worker =
        new SwingWorker<Void, Void>() {

          @Override
          protected void done() {}

          @Override
          protected Void doInBackground() {
            ReportPrinter printer = new ReportPrinter();
            printer.printPart(part);
            return null;
          }
        };
    worker.execute();
  } // GEN-LAST:event_printButtonActionPerformed
コード例 #18
0
ファイル: TreePanel.java プロジェクト: whdc/ieo-beast
  public void importFromFile(final File file) throws IOException, ImportException {

    frame.setBusy();
    SwingWorker<Void, Void> worker =
        new SwingWorker<Void, Void>() {

          // Executed in background thread
          public Void doInBackground() {

            try {

              BufferedReader reader = new BufferedReader(new FileReader(file));

              String line = reader.readLine();
              Tree tree;

              if (line.toUpperCase().startsWith("#NEXUS")) {
                NexusImporter importer = new NexusImporter(reader);
                tree = importer.importTree(null);
              } else {
                NewickImporter importer = new NewickImporter(reader);
                tree = importer.importTree(null);
              }

              // TODO Add taxons from a new tree to that list and display
              // them in Taxa panel
              dataList.taxonList = tree;
              dataList.forestMap.put(file, new TreeModel(tree));
              reader.close();

            } catch (Exception e) {
              Utils.handleException(e);
            } // END: try-catch block

            return null;
          } // END: doInBackground()

          // Executed in event dispatch thread
          public void done() {
            frame.setIdle();
            frame.fireTaxaChanged();
          } // END: done
        };

    worker.execute();
  } // END: importFromFile
コード例 #19
0
    public void actionPerformed(ActionEvent ev) {

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

            // Executed in background thread
            public Void doInBackground() {

              try {

                generateProcessing.setEnabled(false);
                progressBar.setIndeterminate(true);

                // drawPolygonMap.setCam(drawPolygonMap.getCam());

                if (projectionParser.getSelectedIndex() == 0) {
                  drawPolygonMap.setMercatorProjection();
                } else {
                  drawPolygonMap.setEquirrectangularProjection();
                }

                drawPolygonMap.init();

              } catch (Exception e) {

                e.printStackTrace();

                String msg = String.format("Unexpected problem: %s", e.toString());

                JOptionPane.showMessageDialog(null, msg, "Error", JOptionPane.ERROR_MESSAGE);
              }

              return null;
            } // END: doInBackground()

            // Executed in event dispatch thread
            public void done() {

              generateProcessing.setEnabled(true);
              progressBar.setIndeterminate(false);
            }
          };

      worker.execute();
    }
コード例 #20
0
 public MonitoredTask(SwingWorker task, String msg, Component parentComponent) {
   this.task = task;
   // create the progress monitor
   progressMonitor = new ModalProgressMonitor(parentComponent, msg, "", 0, 100);
   progressMonitor.setProgress(0);
   // add ProgressMonitorExample as a listener on CopyFiles;
   // of specific interest is the bound property progress
   task.addPropertyChangeListener(this);
 }
コード例 #21
0
  /**
   * Loads Events fro the local file system
   *
   * @param request
   */
  public void loadEventsFromLocalFiles(final LoadFileRequest request) {

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

          @Override
          public Void doInBackground() {

            if (request.getFilter() == null) {
              request.setFilter(new AllFilter());
            }

            int count = 0;

            List<String> filenames = request.getFilenames();
            int total = filenames.size();

            for (String filename : filenames) {

              count++;

              for (EventLoaderListener l : listeners) {
                l.processingFile(count, total);
              }

              try (InputStream stream = loadEventFromLocalFile(filename); ) {
                processStream(stream, request.getFilter());
              } catch (IOException ioe) {
                ioe.printStackTrace();
              } catch (Exception e) {
                e.printStackTrace();
              }
            }

            for (EventLoaderListener l : listeners) {
              l.finishedLoading();
            }

            return null;
          };
        };

    worker.execute();
  }
コード例 #22
0
  public void showDetails() {
    SwingWorker<String, Void> generateWorker =
        new SwingWorker<String, Void>() {
          Thread t;

          protected String doInBackground() throws Exception {
            t = Thread.currentThread();
            ThreadMgmt.getInstance().addThread(t);

            createGroupDetails();
            return "";
          }

          protected void done() {
            ThreadMgmt.getInstance().removeThread(t);
          }
        };
    generateWorker.execute();
  }
コード例 #23
0
  /** Overlays the files. */
  protected void process() {
    SwingWorker worker;

    m_Processing = true;
    updateButtons();

    worker =
        new SwingWorker() {
          protected StringBuilder m_Errors;

          @Override
          protected Object doInBackground() throws Exception {
            saveSetup();
            m_Errors = new StringBuilder();
            ScriptedPDFOverlay overlay =
                new ScriptedPDFOverlay(
                    new File(m_TextPdfTemplate.getText()),
                    new File(m_TextParams.getText()),
                    new File(m_TextGroovy.getText()),
                    new File(m_TextOutputDir.getText()));
            String errors = overlay.execute();
            if (errors != null) m_Errors.append(errors);
            return null;
          }

          @Override
          protected void done() {
            m_Processing = false;
            updateButtons();
            if (m_Errors.length() > 0) {
              JOptionPane.showMessageDialog(
                  ScriptedPDFOverlayGUI.this,
                  m_Errors.toString(),
                  "Error",
                  JOptionPane.ERROR_MESSAGE);
            }
            super.done();
          }
        };

    worker.execute();
  }
コード例 #24
0
    @Override
    public void actionPerformed(ActionEvent e) {
      final short videoCount = (short) TABLE.getSelectedRows().length;

      // can't happen, but just in case.
      if (videoCount < 1) {
        return;
      }

      // get selected files before we switch to audio and loose the selection
      final List<File> selectedFiles = getSelectedFiles();

      selectAudio();

      String status = I18n.tr("Extracting audio from " + videoCount + " selected videos...");
      if (videoCount == 1) {
        status = I18n.tr("Extracting audio from selected video...");
      }
      LibraryMediator.instance().getLibrarySearch().pushStatus(status);

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

            @Override
            protected Void doInBackground() throws Exception {
              isDemuxing = true;
              demuxFiles(selectedFiles);
              isDemuxing = false;
              return null;
            }

            @Override
            protected void done() {
              int failed = videoCount - demuxedFiles.size();
              String failedStr = (failed > 0) ? " (" + failed + " " + I18n.tr("failed") + ")" : "";
              LibraryMediator.instance()
                  .getLibrarySearch()
                  .pushStatus(I18n.tr("Done extracting audio.") + failedStr);
            }
          };
      demuxWorker.execute();
    }
コード例 #25
0
  private void jBAtualizarActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jBAtualizarActionPerformed

    final Progress p = new Progress();
    p.setVisible(true);
    SwingWorker worker =
        new SwingWorker() {

          @Override
          protected Object doInBackground() throws Exception {
            atualizaTabela();
            return null;
          }

          @Override
          protected void done() {
            p.setVisible(false);
          }
        };
    worker.execute();
  } // GEN-LAST:event_jBAtualizarActionPerformed
コード例 #26
0
  /**
   * (non-Javadoc)
   *
   * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
   * @param e
   */
  public void actionPerformed(ActionEvent e) {
    SwingWorker<Object, Object> worker =
        new SwingWorker<Object, Object>() {

          @Override
          protected Object doInBackground() throws Exception {
            boolean canContinue = RunMultiTimesAction.this.container.canContinue();
            int nbTimes = Integer.parseInt(RunMultiTimesAction.this.textComponent.getText().trim());
            for (int i = 0; i < nbTimes && canContinue; i++) {
              canContinue =
                  RunMultiTimesAction.this.manager.nextStep(RunMultiTimesAction.this.simulation);
              RunMultiTimesAction.this.container.setCanContinue(canContinue);
              RunMultiTimesAction.this.container.modelHasChanged();
              Thread.sleep(100);
            }

            return null;
          }
        };
    worker.execute();
  }
コード例 #27
0
ファイル: DBSettings.java プロジェクト: souley/plier-toolbox
 public void propertyChange(PropertyChangeEvent evt) {
   if ("progress".equalsIgnoreCase(evt.getPropertyName())) {
     int progress = (Integer) evt.getNewValue();
     progressMonitor.setProgress(progress);
     String message = String.format("%d%% complete.\n", (progress == 1) ? 0 : progress);
     progressMonitor.setNote(message);
     if (progressMonitor.isCanceled()) {
       task.cancel(true);
     } else if (progress == 100) {
       mainWin.initGUI();
     }
   }
 }
コード例 #28
0
ファイル: Application.java プロジェクト: maarksco/nodebox
  /**
   * Starts a SwingWorker that loads the application in the background.
   *
   * <p>Called in the event dispatch thread using invokeLater.
   */
  private void run() {
    showProgressDialog();
    startupWorker =
        new SwingWorker<Throwable, String>() {
          @Override
          protected Throwable doInBackground() throws Exception {
            try {
              publish("Starting NodeBox");
              initApplication();
              checkForUpdates();
            } catch (RuntimeException ex) {
              return ex;
            }
            return null;
          }

          @Override
          protected void process(List<String> strings) {
            final String firstString = strings.get(0);
            startupDialog.setMessage(firstString);
          }

          @Override
          protected void done() {
            startingUp.set(false);
            startupDialog.setVisible(false);

            // See if application startup has generated an exception.
            Throwable t;
            try {
              t = get();
            } catch (Exception e) {
              t = e;
            }
            if (t != null) {
              ExceptionDialog ed = new ExceptionDialog(null, t);
              ed.setVisible(true);
              System.exit(-1);
            }

            if (documents.isEmpty() && filesToLoad.isEmpty()) {
              instance.createNewDocument();
            } else {
              for (File f : filesToLoad) {
                openDocument(f);
              }
            }
          }
        };
    startupWorker.execute();
  }
コード例 #29
0
  /*
   * (non-Javadoc)
   *
   * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
   */
  @Override
  public void actionPerformed(ActionEvent e) {
    this.setEnabled(false);
    SwingWorker<Void, Void> worker =
        new SwingWorker<Void, Void>() {
          @Override
          protected Void doInBackground() throws Exception {
            if (console.getMission() == null) {
              GuiUtils.errorMessage(
                  null,
                  I18n.text("Console error"),
                  I18n.text("Selecting Plan: no Mission Loaded in console"));
              return null;
            }

            String checkl =
                (console.getMission().getChecklistsList().size() == 0)
                    ? null
                    : (String)
                        JOptionPane.showInputDialog(
                            console,
                            I18n.text("Choose one of the available Checklists"),
                            I18n.text("Select Checklist"),
                            JOptionPane.QUESTION_MESSAGE,
                            new ImageIcon(),
                            console.getMission().getChecklistsList().keySet().toArray(),
                            console.getMission().getChecklistsList().keySet().iterator().next());

            if (checkl != null) {
              ChecklistType newClone =
                  console.getMission().getChecklistsList().get(checkl).getChecklist().createCopy();
              console.executeCheckList(newClone);
            }
            return null;
          }
        };
    worker.execute();
  }
コード例 #30
0
 // executes in event dispatch thread
 public void propertyChange(PropertyChangeEvent event) {
   // if the operation is finished or has been canceled by
   // the user, take appropriate action
   if (progressMonitor.isCanceled()) {
     task.cancel(true);
   } else if (event.getPropertyName().equals("progress")) {
     // get the % complete from the progress event
     // and set it on the progress monitor
     int progress = ((Integer) event.getNewValue()).intValue();
     progressMonitor.setProgress(progress);
     if (progress >= 100) {
       progressMonitor.close();
     }
   }
 }