List of usage examples for javax.swing SwingWorker SwingWorker
public SwingWorker()
From source file:edu.ku.brc.specify.config.FixAttachments.java
/** * /*from w w w . ja va 2 s.c om*/ */ public void checkForBadAttachments() { int count = getNumberofBadAttachments(); if (count == 0) { AppPreferences.getGlobalPrefs().putBoolean("CHECK_ATTCH_ERR", false); return; } URL url = null; JEditorPane htmlPane; try { url = new URL("http://files.specifysoftware.org/attachment_recovery.html"); htmlPane = new JEditorPane(url); } catch (Exception e) { e.printStackTrace(); htmlPane = new JEditorPane("text/html", //$NON-NLS-1$ "<html><body><h1>Network Error - You must have a network conneciton to get the instructions.</H1></body>"); } JScrollPane scrollPane = UIHelper.createScrollPane(htmlPane); htmlPane.setEditable(false); JPanel panel = new JPanel(new BorderLayout()); panel.add(scrollPane, BorderLayout.CENTER); panel.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6)); CustomDialog infoDlg = new CustomDialog((Dialog) null, "Recovery Information", true, CustomDialog.OKCANCEL, panel); infoDlg.setCancelLabel("Close"); infoDlg.setOkLabel("Print in Browser"); infoDlg.createUI(); infoDlg.setSize(1024, 600); try { hookupAction(infoDlg.getOkBtn(), url != null ? url.toURI() : null); infoDlg.setVisible(true); } catch (Exception ex) { } final String CNT = "CNT"; final SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() { int totalFiles = 0; HashMap<Integer, Vector<Object[]>> resultsHashMap = new HashMap<Integer, Vector<Object[]>>(); HashMap<Integer, String> tblTypeHash = new HashMap<Integer, String>(); HashMap<Integer, String> agentHash = new HashMap<Integer, String>(); HashMap<Integer, AttchTableModel> tableHash = new HashMap<Integer, AttchTableModel>(); ArrayList<JTable> tableList = new ArrayList<JTable>(); ArrayList<Integer> tableIdList = new ArrayList<Integer>(); @Override protected Integer doInBackground() throws Exception { DataProviderSessionIFace session = null; try { // This doesn't need to include the new attachments int[] tableIds = { AccessionAttachment.getClassTableId(), AgentAttachment.getClassTableId(), CollectingEventAttachment.getClassTableId(), CollectionObjectAttachment.getClassTableId(), ConservDescriptionAttachment.getClassTableId(), ConservEventAttachment.getClassTableId(), DNASequencingRunAttachment.getClassTableId(), FieldNotebookAttachment.getClassTableId(), FieldNotebookPageAttachment.getClassTableId(), FieldNotebookPageSetAttachment.getClassTableId(), LoanAttachment.getClassTableId(), LocalityAttachment.getClassTableId(), PermitAttachment.getClassTableId(), PreparationAttachment.getClassTableId(), RepositoryAgreementAttachment.getClassTableId(), TaxonAttachment.getClassTableId() }; Agent userAgent = AppContextMgr.getInstance().getClassObject(Agent.class); int totFiles = 0; firePropertyChange(CNT, 0, 0); int cnt = 0; for (int tableId : tableIds) { Vector<Object[]> results = getImageData(userAgent.getId(), tableId, tblTypeHash); if (results != null && results.size() > 0) { resultsHashMap.put(tableId, results); totFiles += results.size(); //System.out.println(tableId+" -> "+results.size()); } firePropertyChange(CNT, 0, (int) ((double) cnt / (double) tableIds.length * 100.0)); cnt++; } if (resultsHashMap.size() == 0) // Shouldn't happen { return null; } session = DataProviderFactory.getInstance().createSession(); firePropertyChange(CNT, 0, 0); int i = 1; for (int tblId : resultsHashMap.keySet()) { DBTableInfo ti = DBTableIdMgr.getInstance().getInfoById(tblId); Vector<Object[]> dataRows = new Vector<Object[]>(); Vector<Object[]> results = resultsHashMap.get(tblId); for (Object[] row : results) { Integer agentId = (Integer) row[3]; String userName = agentHash.get(agentId); if (userName == null) { userName = BasicSQLUtils.querySingleObj( "SELECT su.Name FROM agent a INNER JOIN specifyuser su ON a.SpecifyUserID = su.SpecifyUserID WHERE a.AgentID = " + row[3]); agentHash.put(agentId, userName); } //userName = i == 1 ? "bill.johnson" : "joe.smith"; int attachJoinID = (Integer) row[4]; String identTitle = getIdentityTitle(session, ti, attachJoinID); String fullPath = (String) row[2]; //fullPath = StringUtils.replace(fullPath, "darwin\\", "darwin2\\"); //boolean doesExist = (new File(fullPath)).exists() && i != 1; boolean doesExist = (new File(fullPath)).exists(); //String str = i != 1 ? "/Users/joe/Desktop/xxx.png" : "/Users/bill/Desktop/xxx.png"; //String fullPath = FilenameUtils.getFullPath(str) + String.format("DSC_%05d.png", i); Object[] rowObjs = new Object[8]; rowObjs[0] = StringUtils.isEmpty(identTitle) ? "" : (identTitle.length() > 30 ? identTitle.substring(0, 30) + "..." : identTitle); rowObjs[1] = FilenameUtils.getName(fullPath); rowObjs[2] = fullPath; rowObjs[3] = userName; rowObjs[4] = doesExist; rowObjs[5] = Boolean.FALSE; rowObjs[6] = row[0]; rowObjs[7] = attachJoinID; dataRows.add(rowObjs); if (doesExist) { totalFiles++; } firePropertyChange(CNT, 0, (int) ((double) i / (double) totFiles * 100.0)); i++; } AttchTableModel model = new AttchTableModel(dataRows); JTable table = new JTable(model); tableHash.put(tblId, model); tableList.add(table); tableIdList.add(tblId); } } catch (Exception ex) { ex.printStackTrace(); } finally { session.close(); } return null; } @Override protected void done() { UIRegistry.clearSimpleGlassPaneMsg(); if (tableList.size() > 0) { displayBadAttachments(tableList, tableIdList, resultsHashMap, tblTypeHash, tableHash, totalFiles); } super.done(); } }; final SimpleGlassPane glassPane = UIRegistry .writeSimpleGlassPaneMsg("Verifying attachments in the repository...", 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:it.illinois.adsc.ema.softgrid.monitoring.ui.SPMainFrame.java
private void startPRXs() { SwingWorker iedWorker = new SwingWorker() { @Override//from w w w. j a va2 s .co m protected Object doInBackground() throws Exception { resultTabbedPane.add(logAreaScrollPane, "Gateway Log"); stateTextArea.setEnabled(false); stateTextArea.setDisabledTextColor(Color.blue); queryScrolPane.getViewport().add(stateTextArea, null); stateTextArea.setText("Initializing Proxy gateway..."); if (!ConfigUtil.PW_TO_SCL_MAPPING.isEmpty()) { it.illinois.adsc.ema.control.conf.generator.ConfigGenerator.generateConfigXml( ConfigUtil.SCL_PATH, ConfigUtil.CONFIG_PEROPERTY_FILE, ConfigUtil.IP); } if (ConfigUtil.SERVER_TYPE.equals("PRX")) { String[] args = { "-f", ConfigUtil.CONFIG_PEROPERTY_FILE, ConfigUtil.SERVER_TYPE, "local" }; SoftGridController.setPRXLogEventListener(SPMainFrame.this); SoftGridController.initiate(args); } else if (ConfigUtil.SERVER_TYPE.equals("ACM")) { String[] args = { ConfigUtil.SERVER_TYPE }; // IEC60870104Server.main(args); } stateTextArea.setText("Gateway Started..!" + "\nGateway Server Protocol : IEC 60870-5-104 " + "\nIED Protocol : IEC 61850"); return null; } }; iedWorker.execute(); }
From source file:com.mirth.connect.client.ui.SettingsPanelServer.java
public void doRestore() { if (getFrame().isSaveEnabled()) { if (!getFrame().alertOkCancel(this, "Your new settings will first be saved. Continue?")) { return; }// www. j ava 2 s. c om if (!doSave()) { return; } } String content = getFrame().browseForFileString("XML"); if (content != null) { try { if (!getFrame().promptObjectMigration(content, "server configuration")) { return; } final ServerConfiguration configuration = ObjectXMLSerializer.getInstance().deserialize(content, ServerConfiguration.class); final JCheckBox deployChannelsCheckBox = new JCheckBox("Deploy all channels after import"); deployChannelsCheckBox.setSelected(true); String warningMessage = "Import configuration from " + configuration.getDate() + "?\nWARNING: This will overwrite all current channels,\nalerts, server properties, and plugin properties.\n"; Object[] params = { warningMessage, new JLabel(" "), deployChannelsCheckBox }; int option = JOptionPane.showConfirmDialog(this, params, "Select an Option", JOptionPane.YES_NO_OPTION); if (option == JOptionPane.YES_OPTION) { final Set<String> alertIds = new HashSet<String>(); for (AlertStatus alertStatus : PlatformUI.MIRTH_FRAME.mirthClient.getAlertStatusList()) { alertIds.add(alertStatus.getId()); } final String workingId = getFrame().startWorking("Restoring server config..."); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { private boolean updateAlerts = false; public Void doInBackground() { try { getFrame().mirthClient.setServerConfiguration(configuration, deployChannelsCheckBox.isSelected()); getFrame().channelPanel.clearChannelCache(); doRefresh(); getFrame().alertInformation(SettingsPanelServer.this, "Your configuration was successfully restored."); updateAlerts = true; } catch (ClientException e) { getFrame().alertThrowable(SettingsPanelServer.this, e); } return null; } public void done() { if (getFrame().alertPanel == null) { getFrame().alertPanel = new DefaultAlertPanel(); } if (updateAlerts) { getFrame().alertPanel.updateAlertDetails(alertIds); } getFrame().stopWorking(workingId); } }; worker.execute(); } } catch (Exception e) { getFrame().alertError(this, "Invalid server configuration file."); } } }
From source file:edu.ku.brc.specify.config.init.DatabasePanel.java
/** * // w w w .j a v a2 s .co m */ public void createDB() { getValues(properties); final String databaseName = dbNameTxt.getText(); final String dbUserName = usernameTxt.getText(); final String dbPwd = passwordTxt.getText(); final String hostName = hostNameTxt.getText(); if (UIRegistry.isMobile()) { DBConnection.clearMobileMachineDir(); File tmpDir = DBConnection.getMobileMachineDir(databaseName); UIRegistry.setEmbeddedDBPath(tmpDir.getAbsolutePath()); } final DatabaseDriverInfo driverInfo = (DatabaseDriverInfo) drivers.getSelectedItem(); String connStrInitial = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName, databaseName, dbUserName, dbPwd, driverInfo.getName()); //System.err.println(connStrInitial); DBConnection.checkForEmbeddedDir(connStrInitial); DBConnection.getInstance().setDriverName(driverInfo.getName()); DBConnection.getInstance().setServerName(hostName); VerifyStatus status = verifyDatabase(properties); if ((isOK == null || !isOK) && status == VerifyStatus.OK) { progressBar.setIndeterminate(true); progressBar.setVisible(true); label.setText(getResourceString("CONN_DB")); createDBBtn.setVisible(false); setUIEnabled(false); DatabasePanel.this.label.setForeground(Color.BLACK); SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() { @Override protected Object doInBackground() throws Exception { isOK = false; DBMSUserMgr mgr = DBMSUserMgr.getInstance(); List<PermissionInfo> perms = null; boolean dbmsOK = false; if (driverInfo.isEmbedded()) { if (checkForProcesses) { ProcessListUtil.checkForMySQLProcesses(null); checkForProcesses = false; } if (UIRegistry.isMobile()) { File mobileTmpDir = DBConnection.getMobileMachineDir(); if (!mobileTmpDir.exists()) { if (!mobileTmpDir.mkdirs()) { System.err.println( "Dir[" + mobileTmpDir.getAbsolutePath() + "] didn't get created!"); // throw exception } DBConnection.setCopiedToMachineDisk(true); } } String newConnStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName, databaseName, dbUserName, dbPwd, driverInfo.getName()); if (driverInfo.isEmbedded()) { //System.err.println(newConnStr); try { Class.forName(driverInfo.getDriverClassName()); // This call will create the database if it doesn't exist DBConnection testDB = DBConnection.createInstance(driverInfo.getDriverClassName(), driverInfo.getDialectClassName(), databaseName, newConnStr, dbUserName, dbPwd); testDB.getConnection(); // Opens the connection if (testDB != null) { testDB.close(); } dbmsOK = true; } catch (Exception ex) { ex.printStackTrace(); } DBConnection.getInstance().setDatabaseName(null); } } else if (mgr.connectToDBMS(dbUserName, dbPwd, hostName)) { perms = mgr.getPermissionsForCurrentUser(); Pair<List<PermissionInfo>, List<PermissionInfo>> missingPerms = PermissionInfo .getMissingPerms(perms, createDBPerms, databaseName); if (missingPerms.getFirst().size() > 0) { final String missingPermStr = PermissionInfo.getMissingPermissionString(mgr, missingPerms.getFirst(), databaseName); SwingUtilities.invokeLater(new Runnable() { /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { UIRegistry.showLocalizedError("SEC_MISSING_PERMS", dbUserName, missingPermStr); } }); dbmsOK = false; } else { dbmsOK = true; } mgr.close(); } if (dbmsOK) { properties.put(DB_SKIP_CREATE, false); if (perms != null) { properties.put(DBUSERPERMS, perms); } firePropertyChange(PROPNAME, 0, 1); try { SpecifySchemaGenerator.generateSchema(driverInfo, hostName, databaseName, dbUserName, dbPwd); // false means create new database, true means update String connStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Create, hostName, databaseName); if (connStr == null) { connStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName, databaseName); } firePropertyChange(PROPNAME, 0, 2); // tryLogin sets up DBConnection if (UIHelper.tryLogin(driverInfo.getDriverClassName(), driverInfo.getDialectClassName(), dbNameTxt.getText(), connStr, dbUserName, dbPwd)) { if (!checkEngineCharSet(properties)) { return false; } isOK = true; firePropertyChange(PROPNAME, 0, 3); Thumbnailer thumb = Thumbnailer.getInstance(); File thumbFile = XMLHelper.getConfigDir("thumbnail_generators.xml"); thumb.registerThumbnailers(thumbFile); thumb.setQuality(0.5f); thumb.setMaxSize(128, 128); File attLoc = UIRegistry.getAppDataSubDir("AttachmentStorage", true); AttachmentManagerIface attachMgr = new FileStoreAttachmentManager(attLoc); AttachmentUtils.setAttachmentManager(attachMgr); AttachmentUtils.setThumbnailer(thumb); } else { errorKey = "NO_LOGIN_ROOT"; } } catch (Exception ex) { errorKey = "DB_UNRECOVERABLE"; } } else { errorKey = "NO_CONN_ROOT"; mgr.close(); } return null; } /* (non-Javadoc) * @see javax.swing.SwingWorker#done() */ @Override protected void done() { super.done(); setUIEnabled(true); progressBar.setIndeterminate(false); progressBar.setVisible(false); updateBtnUI(); createDBBtn.setVisible(!isOK); if (isOK) { label.setText(UIRegistry.getResourceString("DB_CREATED")); setUIEnabled(false); } else { label.setText(UIRegistry.getResourceString(errorKey != null ? errorKey : "ERR_CRE_DB")); UIRegistry.showLocalizedError(errorKey != null ? errorKey : "ERR_CRE_DB"); } } }; worker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { if (PROPNAME.equals(evt.getPropertyName())) { String key = null; switch ((Integer) evt.getNewValue()) { case 1: key = "BLD_SCHEMA"; break; case 2: key = "DB_FRST_LOGIN"; break; case 3: key = "BLD_CACHE"; break; default: break; } if (key != null) { DatabasePanel.this.label.setText(UIRegistry.getResourceString(key)); } } } }); worker.execute(); } else if (status == VerifyStatus.ERROR) { errorKey = "NO_LOGIN_ROOT"; DatabasePanel.this.label.setText(UIRegistry.getResourceString(errorKey)); DatabasePanel.this.label.setForeground(Color.RED); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { UIRegistry.getTopWindow().pack(); } }); } }
From source file:sk.uniza.fri.pds.spotreba.energie.gui.MainGui.java
private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed final NajminajucejsiSpotrebiteliaParams params = new NajminajucejsiSpotrebiteliaParams(); int option = showUniversalInputDialog(params, "10% spotrebiteov s najv?ou spotrebou"); if (option == JOptionPane.OK_OPTION) { new SwingWorker<List, RuntimeException>() { @Override/* w w w .j ava2 s. c o m*/ protected List doInBackground() throws Exception { try { return SeHistoriaService.getInstance().getNajnminajucejsiSpotrebitelia(params); } catch (RuntimeException e) { publish(e); return null; } } @Override protected void done() { try { List data = get(); showJTable(NajminajucejsiSpotrebitel.class, data); } catch (InterruptedException | ExecutionException ex) { Logger.getLogger(MainGui.class.getName()).log(Level.SEVERE, null, ex); } } @Override protected void process(List<RuntimeException> chunks) { if (chunks.size() > 0) { showException("Chyba", chunks.get(0)); } } }.execute(); } }
From source file:com.marginallyclever.makelangelo.MainGUI.java
protected boolean LoadDXF(String filename) { if (ChooseImageConversionOptions(true) == false) return false; // where to save temp output file? final String destinationFile = GetTempDestinationFile(); final String srcFile = filename; TabToLog();/* w w w. j a va2 s. c o m*/ final ProgressMonitor pm = new ProgressMonitor(null, translator.get("Converting"), "", 0, 100); pm.setProgress(0); pm.setMillisToPopup(0); final SwingWorker<Void, Void> s = new SwingWorker<Void, Void>() { public boolean ok = false; @SuppressWarnings("unchecked") @Override public Void doInBackground() { Log("<font color='green'>" + translator.get("Converting") + " " + destinationFile + "</font>\n"); Parser parser = ParserBuilder.createDefaultParser(); double dxf_x2 = 0; double dxf_y2 = 0; OutputStreamWriter out = null; try { out = new OutputStreamWriter(new FileOutputStream(destinationFile), "UTF-8"); DrawingTool tool = machineConfiguration.GetCurrentTool(); out.write(machineConfiguration.GetConfigLine() + ";\n"); out.write(machineConfiguration.GetBobbinLine() + ";\n"); out.write("G00 G90;\n"); tool.WriteChangeTo(out); tool.WriteOff(out); parser.parse(srcFile, DXFParser.DEFAULT_ENCODING); DXFDocument doc = parser.getDocument(); Bounds b = doc.getBounds(); double width = b.getMaximumX() - b.getMinimumX(); double height = b.getMaximumY() - b.getMinimumY(); double cx = (b.getMaximumX() + b.getMinimumX()) / 2.0f; double cy = (b.getMaximumY() + b.getMinimumY()) / 2.0f; double sy = machineConfiguration.GetPaperHeight() * 10 / height; double sx = machineConfiguration.GetPaperWidth() * 10 / width; double scale = (sx < sy ? sx : sy) * machineConfiguration.paper_margin; sx = scale * (machineConfiguration.reverseForGlass ? -1 : 1); // count all entities in all layers Iterator<DXFLayer> layer_iter = (Iterator<DXFLayer>) doc.getDXFLayerIterator(); int entity_total = 0; int entity_count = 0; while (layer_iter.hasNext()) { DXFLayer layer = (DXFLayer) layer_iter.next(); Log("<font color='yellow'>Found layer " + layer.getName() + "</font>\n"); Iterator<String> entity_iter = (Iterator<String>) layer.getDXFEntityTypeIterator(); while (entity_iter.hasNext()) { String entity_type = (String) entity_iter.next(); List<DXFEntity> entity_list = (List<DXFEntity>) layer.getDXFEntities(entity_type); Log("<font color='yellow'>+ Found " + entity_list.size() + " of type " + entity_type + "</font>\n"); entity_total += entity_list.size(); } } // set the progress meter pm.setMinimum(0); pm.setMaximum(entity_total); // convert each entity layer_iter = doc.getDXFLayerIterator(); while (layer_iter.hasNext()) { DXFLayer layer = (DXFLayer) layer_iter.next(); Iterator<String> entity_type_iter = (Iterator<String>) layer.getDXFEntityTypeIterator(); while (entity_type_iter.hasNext()) { String entity_type = (String) entity_type_iter.next(); List<DXFEntity> entity_list = layer.getDXFEntities(entity_type); if (entity_type.equals(DXFConstants.ENTITY_TYPE_LINE)) { for (int i = 0; i < entity_list.size(); ++i) { pm.setProgress(entity_count++); DXFLine entity = (DXFLine) entity_list.get(i); Point start = entity.getStartPoint(); Point end = entity.getEndPoint(); double x = (start.getX() - cx) * sx; double y = (start.getY() - cy) * sy; double x2 = (end.getX() - cx) * sx; double y2 = (end.getY() - cy) * sy; // is it worth drawing this line? double dx = x2 - x; double dy = y2 - y; if (dx * dx + dy * dy < tool.GetDiameter() / 2.0) { continue; } dx = dxf_x2 - x; dy = dxf_y2 - y; if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) { if (tool.DrawIsOn()) { tool.WriteOff(out); } tool.WriteMoveTo(out, (float) x, (float) y); } if (tool.DrawIsOff()) { tool.WriteOn(out); } tool.WriteMoveTo(out, (float) x2, (float) y2); dxf_x2 = x2; dxf_y2 = y2; } } else if (entity_type.equals(DXFConstants.ENTITY_TYPE_SPLINE)) { for (int i = 0; i < entity_list.size(); ++i) { pm.setProgress(entity_count++); DXFSpline entity = (DXFSpline) entity_list.get(i); entity.setLineWeight(30); DXFPolyline polyLine = DXFSplineConverter.toDXFPolyline(entity); boolean first = true; for (int j = 0; j < polyLine.getVertexCount(); ++j) { DXFVertex v = polyLine.getVertex(j); double x = (v.getX() - cx) * sx; double y = (v.getY() - cy) * sy; double dx = dxf_x2 - x; double dy = dxf_y2 - y; if (first == true) { first = false; if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) { // line does not start at last tool location, lift and move. if (tool.DrawIsOn()) { tool.WriteOff(out); } tool.WriteMoveTo(out, (float) x, (float) y); } // else line starts right here, do nothing. } else { // not the first point, draw. if (tool.DrawIsOff()) tool.WriteOn(out); if (j < polyLine.getVertexCount() - 1 && dx * dx + dy * dy < tool.GetDiameter() / 2.0) continue; // less than 1mm movement? Skip it. tool.WriteMoveTo(out, (float) x, (float) y); } dxf_x2 = x; dxf_y2 = y; } } } else if (entity_type.equals(DXFConstants.ENTITY_TYPE_POLYLINE)) { for (int i = 0; i < entity_list.size(); ++i) { pm.setProgress(entity_count++); DXFPolyline entity = (DXFPolyline) entity_list.get(i); boolean first = true; for (int j = 0; j < entity.getVertexCount(); ++j) { DXFVertex v = entity.getVertex(j); double x = (v.getX() - cx) * sx; double y = (v.getY() - cy) * sy; double dx = dxf_x2 - x; double dy = dxf_y2 - y; if (first == true) { first = false; if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) { // line does not start at last tool location, lift and move. if (tool.DrawIsOn()) { tool.WriteOff(out); } tool.WriteMoveTo(out, (float) x, (float) y); } // else line starts right here, do nothing. } else { // not the first point, draw. if (tool.DrawIsOff()) tool.WriteOn(out); if (j < entity.getVertexCount() - 1 && dx * dx + dy * dy < tool.GetDiameter() / 2.0) continue; // less than 1mm movement? Skip it. tool.WriteMoveTo(out, (float) x, (float) y); } dxf_x2 = x; dxf_y2 = y; } } } } } // entities finished. Close up file. tool.WriteOff(out); tool.WriteMoveTo(out, 0, 0); ok = true; } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); } } pm.setProgress(100); return null; } @Override public void done() { pm.close(); Log("<font color='green'>" + translator.get("Finished") + "</font>\n"); PlayConversionFinishedSound(); if (ok) { LoadGCode(destinationFile); TabToDraw(); } Halt(); } }; s.addPropertyChangeListener(new PropertyChangeListener() { // Invoked when task's progress property changes. public void propertyChange(PropertyChangeEvent evt) { if ("progress" == evt.getPropertyName()) { int progress = (Integer) evt.getNewValue(); pm.setProgress(progress); String message = String.format("%d%%\n", progress); pm.setNote(message); if (s.isDone()) { Log("<font color='green'>" + translator.get("Finished") + "</font>\n"); } else if (s.isCancelled() || pm.isCanceled()) { if (pm.isCanceled()) { s.cancel(true); } Log("<font color='green'>" + translator.get("Cancelled") + "</font>\n"); } } } }); s.execute(); return true; }
From source file:org.eumetsat.metop.visat.SounderInfoView.java
private void updateSpectrumDataset(final Ifov selectedIfov, final EpsFile epsFile) { final SwingWorker<XYSeries, Object> worker = new SwingWorker<XYSeries, Object>() { @Override/*from w w w . j a v a2s .c o m*/ protected XYSeries doInBackground() throws Exception { return createSpectrumPlotXYSeries(readSceneRadiances(epsFile, selectedIfov)); } @Override protected void done() { try { spectrumDataset.removeAllSeries(); final XYSeries series = get(); spectrumDataset.addSeries(series); } catch (InterruptedException e) { spectrumPlot.setNoDataMessage(IO_ERROR); } catch (ExecutionException e) { spectrumPlot.setNoDataMessage(IO_ERROR); } } }; worker.execute(); }
From source file:com.enderville.enderinstaller.ui.Installer.java
@Override public void hyperlinkUpdate(final HyperlinkEvent e) { if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED) { return;// w w w . ja v a 2 s. com } SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() { @Override protected Object doInBackground() throws Exception { try { String url = e.getURL().toExternalForm(); Desktop.getDesktop().browse(URI.create(url)); } catch (Exception e) { e.printStackTrace(); } return null; } }; worker.execute(); }
From source file:sk.uniza.fri.pds.spotreba.energie.gui.MainGui.java
private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed final ZamestnanecRegionParams params = new ZamestnanecRegionParams(); int option = showUniversalInputDialog(params, "Zamestnanci v regine"); if (option == JOptionPane.OK_OPTION) { new SwingWorker<List, RuntimeException>() { @Override// w ww .ja va 2 s . co m protected List doInBackground() throws Exception { try { return SeZamestnanecService.getInstance().findInRegion(params); } catch (RuntimeException e) { publish(e); return null; } } @Override protected void done() { try { List data = get(); showJTable(SeZamestnanecInfo.class, data); } catch (InterruptedException | ExecutionException ex) { Logger.getLogger(MainGui.class.getName()).log(Level.SEVERE, null, ex); } } @Override protected void process(List<RuntimeException> chunks) { if (chunks.size() > 0) { showException("Chyba", chunks.get(0)); } } }.execute(); } }
From source file:be.ac.ua.comp.scarletnebula.gui.windows.GUI.java
public void refreshSelectedServers() { final int indices[] = serverList.getSelectedIndices(); final Collection<Server> servers = serverListModel.getVisibleServersAtIndices(indices); // fillRightPartition(); (new SwingWorker<Exception, Object>() { @Override// w w w. ja v a 2s .c om protected Exception doInBackground() throws Exception { for (final Server server : servers) { try { server.refresh(); } catch (final ServerDisappearedException e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { log.info("Server disappeared.", e); removeServer(server); } }); } catch (final Exception e) { return e; } } return null; } @Override public void done() { try { final Exception result = get(); if (result != null) { log.error("Error while refreshing", result); error(result.getLocalizedMessage()); } } catch (final Exception ignore) { } } }).execute(); }