List of usage examples for javax.swing SwingWorker SwingWorker
public SwingWorker()
From source file:com.opendoorlogistics.studio.appframe.AppFrame.java
@Override public void postAsynchronousDatastoreModify(DatastoreModifier modifier) { if (getLoadedDatastore() == null) { JOptionPane.showMessageDialog(AppFrame.this, "Cannot execute " + modifier.name() + " as no datastore is loaded."); return;/*ww w . jav a 2 s .c o m*/ } new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { new PluginDatastoreModifierTask(AppFrame.this, modifier).executeNonEDT(); return null; } }.execute(); ; }
From source file:com.nbt.TreeFrame.java
private void createAndShowTileCanvas(World world) { String title = world.getName(); JFrame frame = new JFrame(title); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.tileCanvas = new TileCanvas(world) { @Override/*from www . j av a2 s . c o m*/ protected void blockClicked(final Block block) { Cursor waitCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR); setCursor(waitCursor); SwingWorkerUnlimited.execure(new SwingWorker<TreePath, Void>() { @Override protected TreePath doInBackground() throws Exception { WorldBlock b = (WorldBlock) block; NBTChunk chunk = (NBTChunk) b.getChunk(); NBTRegion region = (NBTRegion) chunk.getRegion(); Tag<?> chunkTag = chunk.getTag(); CompoundTag compoundTag = (CompoundTag) chunkTag; Tag<?> level = compoundTag.search("Level"); CompoundTag levelTag = (CompoundTag) level; Tag<?> blocks = levelTag.search("Blocks"); ByteArrayTag blocksTag = (ByteArrayTag) blocks; int index = b.getIndex(); Object child = blocksTag.getChild(index); return treeTable.getPathForNode(region).pathByAddingChild(chunk).pathByAddingChild(level) .pathByAddingChild(blocks).pathByAddingChild(child); } @Override protected void done() { Cursor defaultCursor = Cursor.getDefaultCursor(); setCursor(defaultCursor); try { TreePath path = get(); selectAndScroll(path); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); Throwable cause = ExceptionUtils.getRootCause(e); showErrorDialog(cause.getMessage()); return; } } }); } }; tileCanvas.restore(); frame.add(tileCanvas); frame.pack(); frame.setVisible(true); }
From source file:edu.ku.brc.specify.datamodel.busrules.CollectionObjectBusRules.java
/** * //from w w w . j a v a2s . co m */ public void doCreateBatchOfColObj(final Pair<String, String> catNumPair) { if (catNumPair.getFirst().equals(catNumPair.getSecond())) { return; } DBFieldInfo CatNumFld = DBTableIdMgr.getInstance().getInfoById(CollectionObject.getClassTableId()) .getFieldByColumnName("CatalogNumber"); final UIFieldFormatterIFace formatter = CatNumFld.getFormatter(); if (!formatter.isIncrementer()) { //XXX this will have been checked earlier, right? UIRegistry.showLocalizedError(NonIncrementingCatNum); return; } final Vector<String> nums = new Vector<String>(); processBatchContents(catNumPair, false, false, nums); SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() { private Vector<Pair<Integer, String>> objectsAdded = new Vector<Pair<Integer, String>>(); private Vector<String> objectsNotAdded = new Vector<String>(); private RecordSet batchRS; //private boolean invalidEntry = false; /* (non-Javadoc) * @see javax.swing.SwingWorker#doInBackground() */ @Override protected Integer doInBackground() throws Exception { String catNum = catNumPair.getFirst(); Integer collId = AppContextMgr.getInstance().getClassObject(Collection.class).getId(); String coIdSql = "select CollectionObjectID from collectionobject where CollectionMemberID = " + collId + " and CatalogNumber = '"; objectsAdded.add(new Pair<Integer, String>( (Integer) BasicSQLUtils.querySingleObj(coIdSql + catNum + "'"), catNum)); int cnt = 0; CollectionObject co = null; //CollectionObject carryForwardCo = (CollectionObject )formViewObj.getDataObj(); CollectionObject carryForwardCo; DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession(); try { carryForwardCo = session.get(CollectionObject.class, ((CollectionObject) formViewObj.getDataObj()).getId()); } finally { session.close(); } Thread.sleep(666); //Perhaps this is unnecessary, but it seems //to prevent sporadic "illegal access to loading collection" hibernate errors. try { for (String currentCat : nums) { try { co = new CollectionObject(); co.initialize(); //Collection doesn't get set in co.initialize(), or carryForward, but it needs to be set. co.setCollection(AppContextMgr.getInstance().getClassObject(Collection.class)); //ditto, but doesn't so much need to be set co.setModifiedByAgent(carryForwardCo.getModifiedByAgent()); co.setCatalogNumber(currentCat); formViewObj.setNewObject(co); if (formViewObj.saveObject()) { objectsAdded.add(new Pair<Integer, String>( (Integer) BasicSQLUtils .querySingleObj(coIdSql + co.getCatalogNumber() + "'"), co.getCatalogNumber())); } else { objectsNotAdded.add(formatter.formatToUI(co.getCatalogNumber()).toString()); } } catch (Exception ex) { log.error(ex); objectsNotAdded.add(formatter.formatToUI(currentCat) + ": " + (ex.getLocalizedMessage() == null ? "" : ex.getLocalizedMessage())); } cnt++; firePropertyChange(GLASSKEY, 0, cnt); } firePropertyChange(GLASSKEY, 0, nums.size()); } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(Uploader.class, ex); } formViewObj.setDataObj(carryForwardCo); saveBatchObjectsToRS(); return objectsAdded.size(); } /** * Save the objects added to a Recordset */ protected void saveBatchObjectsToRS() { batchRS = new RecordSet(); batchRS.initialize(); batchRS.setDbTableId(CollectionObject.getClassTableId()); String name = getResourceString(BatchRSBaseName) + " " + formatter.formatToUI(catNumPair.getFirst()) + "-" + formatter.formatToUI(catNumPair.getSecond()); if (objectsNotAdded.size() > 0) { name += "-" + UIRegistry.getResourceString(IncompleteSaveFlag); } batchRS.setName(name); for (Pair<Integer, String> obj : objectsAdded) { batchRS.addItem(obj.getFirst()); } DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession(); boolean transOpen = false; try { BusinessRulesIFace busRule = DBTableIdMgr.getInstance().getBusinessRule(RecordSet.class); if (busRule != null) { busRule.beforeSave(batchRS, session); } batchRS.setTimestampCreated(new Timestamp(System.currentTimeMillis())); batchRS.setOwner(AppContextMgr.getInstance().getClassObject(SpecifyUser.class)); session.beginTransaction(); transOpen = true; session.save(batchRS); if (busRule != null) { if (!busRule.beforeSaveCommit(batchRS, session)) { session.rollback(); throw new Exception("Business rules processing failed"); } } session.commit(); transOpen = false; if (busRule != null) { busRule.afterSaveCommit(batchRS, session); } } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(Uploader.class, ex); if (transOpen) { session.rollback(); } } } /** * Add the batch RS to the RecordSetTask UI */ protected void addBatchRSToUI() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { CommandAction cmd = new CommandAction(RecordSetTask.RECORD_SET, RecordSetTask.ADD_TO_NAV_BOX); cmd.setData(batchRS); CommandDispatcher.dispatch(cmd); } }); } /* (non-Javadoc) * @see javax.swing.SwingWorker#done() */ @Override protected void done() { super.done(); processingSeries.set(false); addBatchRSToUI(); UIRegistry.clearSimpleGlassPaneMsg(); if (objectsNotAdded.size() == 0) { UIRegistry.displayLocalizedStatusBarText(BatchSaveSuccess, formatter.formatToUI(catNumPair.getFirst()), formatter.formatToUI(catNumPair.getSecond())); } else { showBatchErrorObjects(objectsNotAdded, BatchSaveErrorsTitle, BatchSaveErrors); } } }; final SimpleGlassPane gp = UIRegistry.writeSimpleGlassPaneMsg(getI10N("SAVING_BATCH"), 24); gp.setProgress(0); worker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { if (GLASSKEY.equals(evt.getPropertyName())) { double value = (double) ((Integer) evt.getNewValue()).intValue(); int percent = (int) (value / ((double) nums.size()) * 100.0); gp.setProgress(percent); } } }); processingSeries.set(true); worker.execute(); // try { // worker.get(); // } catch (Exception ex) { // ex.printStackTrace(); // } }
From source file:es.emergya.ui.gis.popups.ConsultaHistoricos.java
private synchronized void updateRecursos() { if (updateRecursos != null) { updateRecursos.cancel(true);// w w w. j a v a2 s. c om } updateRecursos = new SwingWorker<String, String>() { private String[] recursosEnPeriodos = new String[0]; private Incidencia[] incidenciasEnPeriodos = new Incidencia[0]; @Override protected String doInBackground() throws Exception { cargando.setIcon(LogicConstants.getIcon("anim_calculando")); Calendar ini = null; Calendar fin = null; if (!soloUltimas.isSelected()) { ini = getFechaIni(); fin = getFechaFin(); } if (ini != null && fin != null && ini.after(fin)) { return null; } List<Long> idZonas = new ArrayList<Long>(); // for (Object o : zona.getSelectedValues()) { // if (o instanceof Zona) { // idZonas.add(((Zona) o).getId()); // } // } long[] zonas = new long[idZonas.size()]; for (int i = 0; i < zonas.length; i++) { zonas[i] = idZonas.get(i); } recursosEnPeriodos = getRecursosEnPeriodo(Authentication.getUsuario().getNombreUsuario(), ini, fin, zonas); incidenciasEnPeriodos = getIncidenciasEnPeriodo(Authentication.getUsuario().getNombreUsuario(), ini, fin, zonas); return null; } @Override protected void done() { synchronized (recursos) { log.trace("Cargamos los recursos"); ((DefaultListModel) recursos.getModel()).removeAllElements(); for (String recurso : recursosEnPeriodos) { log.trace("Mostramos en la ventana de consulta " + recurso); ((DefaultListModel) recursos.getModel()).addElement(recurso); } } synchronized (incidencias) { ((DefaultListModel) incidencias.getModel()).removeAllElements(); for (Incidencia i : incidenciasEnPeriodos) { log.trace("Mostramos en la ventana de consulta " + i); ((DefaultListModel) incidencias.getModel()).addElement(i); } } limpiar.setEnabled(true); recursos.repaint(); incidencias.repaint(); cargando.setIcon(LogicConstants.getIcon("48x48_transparente")); cargando.repaint(); updateRecursos = null; } }; updateRecursos.execute(); }
From source file:edu.ku.brc.specify.tasks.ReportsBaseTask.java
/** * Prints a JTable's model as a Grid Report. * /* w ww. j a v a 2 s . co m*/ * @param cmdAction the command holding the actual JTable object */ protected void printGrid(final CommandAction cmdAction) { String pageTitle = cmdAction.getProperty("gridtitle").toString(); final PageSetupDlg pageSetup = new PageSetupDlg(); pageSetup.createUI(); pageSetup.setPageTitle(pageTitle); pageSetup.setVisible(true); if (pageSetup.isCancelled()) { return; } SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() { protected Exception excpt = null; /* (non-Javadoc) * @see javax.swing.SwingWorker#doInBackground() */ @Override protected Integer doInBackground() throws Exception { JTable table = (JTable) cmdAction.getProperty("jtable"); if (table != null) { try { LabelsPane labelsPane = new LabelsPane(name, ReportsBaseTask.this, null); DynamicReport dr = buildReport(table.getModel(), pageSetup); JRDataSource ds = new JRTableModelDataSource(table.getModel()); JasperPrint jp = DynamicJasperHelper.generateJasperPrint(dr, new ClassicLayoutManager(), ds); labelsPane.reportFinished(jp); SubPaneMgr.getInstance().addPane(labelsPane); } catch (Exception ex) { excpt = ex; ex.printStackTrace(); } } return null; } @Override protected void done() { super.done(); UIRegistry.getStatusBar().setProgressDone(PRINT_GRID); UIRegistry.clearSimpleGlassPaneMsg(); if (excpt != null) { UIRegistry.getStatusBar().setErrorMessage(getResourceString("REP_ERR_GRDRPT"), excpt); } } }; final JStatusBar statusBar = UIRegistry.getStatusBar(); statusBar.setIndeterminate(PRINT_GRID, true); UIRegistry.writeSimpleGlassPaneMsg( getLocalizedMessage("REP_GRID_RPT", cmdAction.getProperty("gridtitle").toString()), 24); backupWorker.execute(); }
From source file:mainGUI.TrainingJFrame.java
private void startTrainButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startTrainButtonActionPerformed series.clear();//from w w w . j a va 2 s. c o m stopTrainButton.setEnabled(true); startTrainButton.setEnabled(false); trainingHelper = new TrainingHelper(neuralNet, trainingDataSet, trainingDataSet.subDataSet(0, 700), learningParameters); epochProgressBar.setValue(0); epochProgressBar.setMaximum(trainingDataSet.size()); SwingWorker<Boolean, TrainingPublishable> worker = new SwingWorker<Boolean, TrainingPublishable>() { @Override protected Boolean doInBackground() throws Exception { trainingHelper.setOnItemTrainListener(new OnItemTrainListener() { @Override public void onItemTrain(int trainingDataItemIndex) { publish(new TrainingPublishable(trainingDataItemIndex)); } }); trainingHelper.setOnEpochFinishListner(new OnEpochFinishListener() { @Override public void onEpochFinish() { publish(new TrainingPublishable(neuralNet.deepClone(), trainingHelper.getEpoch(), trainingHelper.getEpochMSE())); } }); trainingHelper.train(); return true; } @Override protected void done() { System.out.println("Training Done"); } @Override protected void process(List<TrainingPublishable> chunks) { for (TrainingPublishable chunk : chunks) { if (chunk.neuralNet == null) { if (chunk.trainingDataItemIndex != -1) { epochProgressBar.setValue(chunk.trainingDataItemIndex); epochProgressBar.setString(chunk.trainingDataItemIndex + " of 60000"); } } else { System.gc(); System.out.println("Calling GC"); logHeap(); epochFinished(chunk.neuralNet, chunk.epochNum, chunk.MSE); } } } }; worker.execute(); }
From source file:de.cismet.cids.custom.objecteditors.wunda_blau.WebDavPicturePanel.java
/** * DOCUMENT ME!/* w ww . j av a 2s . c o m*/ */ private void initMap() { if (cidsBean != null) { final Object geoObj = cidsBean.getProperty(geoFieldProp); if (geoObj instanceof Geometry) { new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { try { final Geometry pureGeom = CrsTransformer.transformToGivenCrs((Geometry) geoObj, ClientAlkisConf.getInstance().getSrsService()); if (LOG.isDebugEnabled()) { LOG.debug("ALKISConstatns.Commons.GeoBUffer: " + ClientAlkisConf.getInstance().getGeoBuffer()); } final XBoundingBox box = new XBoundingBox( pureGeom.getEnvelope().buffer(ClientAlkisConf.getInstance().getGeoBuffer())); final double diagonalLength = Math .sqrt((box.getWidth() * box.getWidth()) + (box.getHeight() * box.getHeight())); if (LOG.isDebugEnabled()) { LOG.debug("Buffer for map: " + diagonalLength); } final XBoundingBox bufferedBox = new XBoundingBox( box.getGeometry().buffer(diagonalLength)); final ActiveLayerModel mappingModel = new ActiveLayerModel(); mappingModel.setSrs(ClientAlkisConf.getInstance().getSrsService()); mappingModel.addHome(new XBoundingBox(bufferedBox.getX1(), bufferedBox.getY1(), bufferedBox.getX2(), bufferedBox.getY2(), ClientAlkisConf.getInstance().getSrsService(), true)); final SimpleWMS swms = new SimpleWMS( new SimpleWmsGetMapUrl(ClientAlkisConf.getInstance().getMapCallString())); swms.setName("Treppe"); final StyledFeature dsf = new DefaultStyledFeature(); dsf.setGeometry(pureGeom); dsf.setFillingPaint(new Color(1, 0, 0, 0.5f)); dsf.setLineWidth(3); dsf.setLinePaint(new Color(1, 0, 0, 1f)); // add the raster layer to the model mappingModel.addLayer(swms); // set the model map.setMappingModel(mappingModel); // initial positioning of the map final int duration = map.getAnimationDuration(); map.setAnimationDuration(0); map.gotoInitialBoundingBox(); // interaction mode map.setInteractionMode(MappingComponent.ZOOM); // finally when all configurations are done ... map.unlock(); map.addCustomInputListener("MUTE", new PBasicInputEventHandler() { @Override public void mouseClicked(final PInputEvent evt) { if (evt.getClickCount() > 1) { final CidsBean bean = cidsBean; ObjectRendererUtils.switchToCismapMap(); ObjectRendererUtils.addBeanGeomAsFeatureToCismapMap(bean, false); } } }); map.setInteractionMode("MUTE"); map.getFeatureCollection().addFeature(dsf); map.setAnimationDuration(duration); } catch (final Exception ex) { LOG.error("error while init map", ex); } return null; } }.execute(); } } }
From source file:com.xilinx.virtex7.MainScreen.java
private Container createContentPane() { JPanel contentPane = new JPanel(); contentPane.setLayout(new BorderLayout()); contentPane.setOpaque(true);/* w w w .j a v a 2 s . c o m*/ mainPanel = new JPanel(new BorderLayout()); mainPanel.setBounds(0, 0, minWidth, minHeight); testPanel = new JPanel(new BorderLayout()); ttabs = new JTabbedPane(); ttabs.add("DATAPATH 0&1", testAndStats()); if (mode == LandingPage.PERFORMANCE_MODE_RAW || mode == LandingPage.PERFORMANCE_MODE_RAW_DV || mode == LandingPage.APPLICATION_MODE || mode == LandingPage.APPLICATION_MODE_P2P) // condition for placing dynamic tabs. a kcah ttabs.add("DATAPATH 2&3", testAndStatsSecondTab()); else testAndStatsSecondTab(); testPanel.add(ttabs, BorderLayout.CENTER); testPanel.add(messageBox(), BorderLayout.PAGE_END); mainPanel.add(testPanel, BorderLayout.LINE_START); //Make the center component big, since that's the //typical usage of BorderLayout. tabs = new JTabbedPane(); mainPanel.add(tabs, BorderLayout.CENTER); tabs.add("System Monitor", pciInfo()); tabs.add("Performance Plots", plotPanel()); mainPanel.setOpaque(true); try { imagePanel = new ImageBackgroundPanel(blockDiagram, false); } catch (Exception e) { } /*imagePanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Design Block Diagram"), BorderFactory.createEmptyBorder(5,5,5,5)));*/ imagePanel.setBackground(Color.WHITE); imagePanel.setSize(minWidth, minHeight); imagePanel.setLocation(0, 0); imagePanel.setOpaque(true); final JLayeredPane layeredPane = new JLayeredPane(); layeredPane.setPreferredSize(new Dimension(minWidth, minHeight)); layeredPane.add(mainPanel, JLayeredPane.DEFAULT_LAYER, 0); layeredPane.add(imagePanel, JLayeredPane.DEFAULT_LAYER, 0); layeredPane.addComponentListener(new ComponentListener() { @Override public void componentResized(ComponentEvent ce) { mainPanel.setBounds(0, 0, Math.max(minWidth, layeredPane.getWidth()), Math.max(minHeight, layeredPane.getHeight())); if (layeredPane.getWidth() > 1024) { tplotPanel.setPreferredSize(new Dimension(300, 100)); } else { tplotPanel.setPreferredSize(new Dimension(200, 100)); } imagePanel.setSize(mainPanel.getWidth(), mainPanel.getHeight()); imagePanel.setLocation(0, 0); mainPanel.repaint(); } @Override public void componentMoved(ComponentEvent ce) { //throw new UnsupportedOperationException("Not supported yet."); } @Override public void componentShown(ComponentEvent ce) { //throw new UnsupportedOperationException("Not supported yet."); } @Override public void componentHidden(ComponentEvent ce) { //throw new UnsupportedOperationException("Not supported yet."); } }); // on top, but invisible initially imagePanel.setVisible(false); JPanel bpanel = new JPanel(new BorderLayout()); final JButton button = new JButton( "<html><b>B<br>L<br>O<br>C<br>K<br> <br>D<br>I<br>A<br>G<br>R<br>A<br>M<br></b></html>"); button.setToolTipText("Click here to see the block diagram"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { adjustSelectionPanel(); } }); bpanel.add(button, BorderLayout.CENTER); contentPane.add(layeredPane, BorderLayout.CENTER); contentPane.add(button, BorderLayout.EAST); JPanel panel = new JPanel(new BorderLayout()); JLabel mLabel = new JLabel(modeText, JLabel.CENTER); mLabel.setFont(new Font(modeText, Font.BOLD, 15)); panel.add(mLabel, BorderLayout.PAGE_START); JPanel ledPanel = new JPanel(new BorderLayout()); JPanel iledPanel = new JPanel(); iledPanel.setLayout(new BoxLayout(iledPanel, BoxLayout.X_AXIS)); led_ddr3_1 = new JLabel("DDR3 0", new ImageIcon(led1), JLabel.CENTER); led_ddr3_2 = new JLabel("DDR3 1", new ImageIcon(led1), JLabel.CENTER); led_phy0 = new JLabel("PHY 0", new ImageIcon(led1), JLabel.CENTER); led_phy1 = new JLabel("PHY 1", new ImageIcon(led1), JLabel.CENTER); led_phy2 = new JLabel("PHY 2", new ImageIcon(led1), JLabel.CENTER); led_phy3 = new JLabel("PHY 3", new ImageIcon(led1), JLabel.CENTER); JPanel le1 = new JPanel(new BorderLayout()); le1.add(led_ddr3_1, BorderLayout.CENTER); JPanel le2 = new JPanel(new BorderLayout()); le2.add(led_ddr3_2, BorderLayout.CENTER); JPanel le3 = new JPanel(new BorderLayout()); le3.add(led_phy0, BorderLayout.CENTER); JPanel le4 = new JPanel(new BorderLayout()); le4.add(led_phy1, BorderLayout.CENTER); JPanel le5 = new JPanel(new BorderLayout()); le5.add(led_phy2, BorderLayout.CENTER); JPanel le6 = new JPanel(new BorderLayout()); le6.add(led_phy3, BorderLayout.CENTER); iledPanel.add(le1); iledPanel.add(le2); iledPanel.add(le3); iledPanel.add(le4); iledPanel.add(le5); iledPanel.add(le6); if (mode == LandingPage.PERFORMANCE_MODE_RAW || mode == LandingPage.PERFORMANCE_MODE_RAW_DV) { startAll_tooltip = "This will start tests on all data paths"; startAlltests = new JButton("Start All"); startAlltests.setToolTipText(startAll_tooltip); startAlltests.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if (startAlltests.getText().equals("Start All")) { startAll_tooltip = "This will stop tests on all data paths"; startAlltests.setToolTipText(startAll_tooltip); // check whether any tests are already started String message = ""; if (testStarted || testStarted1) message = "Test(s) on Path 0&1 are running. Cannot do Start All"; if (testStarted2 || testStarted3) { if (message.length() > 0) // test 1 and 0 are also running message = "Test(s) on Path 0&1 and 2&3 are running. Cannot do Start All"; else message = "Test(s) on Path 2&3 are running. Cannot do Start All"; } if (message.length() > 0) { JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE); } else { String ledsMsg = checkLedsState(); // condition to check the ddr and py leds are enable or not if (ledsMsg.length() == 0) { startAlltests.setEnabled(false); startAlltests.setText("Stop All"); startTest.doClick(); stest.doClick(); s3test.doClick(); s4test.doClick(); // disable all buttons startTest.setEnabled(false); stest.setEnabled(false); s3test.setEnabled(false); s4test.setEnabled(false); startAlltests.setEnabled(true); } else {// shows alert when leds are disabled JOptionPane.showMessageDialog(null, ledsMsg, "Error", JOptionPane.ERROR_MESSAGE); } } } else { startAlltests.setEnabled(false); startAll_tooltip = "This will start tests on all data paths"; startAlltests.setToolTipText(startAll_tooltip); /* startTest.setEnabled(true); stest.setEnabled(true); s3test.setEnabled(true); s4test.setEnabled(true); s3test.doClick(); s4test.doClick(); startTest.doClick(); stest.doClick(); */ SwingWorker worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { try { stopTest4(); s4test.setEnabled(false); stopTest3(); s3test.setEnabled(false); stopTest2(); stest.setEnabled(false); stopTest1(); startTest.setEnabled(false); startAlltests.setText("Start All"); startAlltests.setEnabled(true); startTest.setEnabled(true); stest.setEnabled(true); s3test.setEnabled(true); s4test.setEnabled(true); } catch (Exception e) { e.printStackTrace(); } return null; } }; worker.execute(); } } }); iledPanel.add(startAlltests); } ledPanel.add(iledPanel, BorderLayout.CENTER); //tstats.add(ledPanel); panel.add(ledPanel, BorderLayout.CENTER); contentPane.add(panel, BorderLayout.PAGE_START); return contentPane; }
From source file:com.josescalia.tumblr.form.TumblrImageViewer.java
private void setDisplay(List<DownloadableImage> downloadableImageList) { frame = (MainFrame) this.getTopLevelAncestor(); form = this;// w ww .j a v a 2s . c o m final List<DownloadableImage> downloadableImages = downloadableImageList; form.setCursor(new Cursor(Cursor.WAIT_CURSOR)); frame.setCursor(new Cursor(Cursor.WAIT_CURSOR)); frame.startProgressBar("Viewing"); if (downloadableImages != null && downloadableImages.size() > 0) { new SwingWorker<String, String>() { @Override protected String doInBackground() throws Exception { String sReturn = ""; for (DownloadableImage image : downloadableImages) { String fileName = image.getUrl().substring(image.getUrl().lastIndexOf("/") + 1); String downloadUrl = image.getUrl(); if (sReturn.length() > 0) { sReturn += "<br>"; } sReturn += "<img src='file:///" + BinaryCacheUtil.getBinaryImagePath(".cache", fileName, downloadUrl) + "'>"; } return sReturn; } @Override protected void done() { try { setImageDisplay(get()); } catch (InterruptedException e) { logger.error(e); } catch (ExecutionException e) { logger.error(e); } form.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); frame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); frame.stopProgressBar(""); } }.execute(); } }
From source file:com.nbt.TreeFrame.java
public void doExport(final File file) { textFile.setText(file.getAbsolutePath()); Cursor waitCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR); setCursor(waitCursor);/*from w w w .jav a 2 s . c o m*/ NBTTreeTableModel model = treeTable.getTreeTableModel(); final Object root = model.getRoot(); SwingWorkerUnlimited.execure(new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { if (root instanceof Saveable) { Saveable saveable = (Saveable) root; if (saveable.hasChanged()) saveable.save(); } return null; } @Override protected void done() { Cursor defaultCursor = Cursor.getDefaultCursor(); setCursor(defaultCursor); try { get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); Throwable cause = ExceptionUtils.getRootCause(e); showErrorDialog(cause.getMessage()); return; } } }); }