List of usage examples for javax.swing SwingWorker SwingWorker
public SwingWorker()
From source file:edu.ku.brc.specify.tasks.subpane.VisualQueryPanel.java
/** * @throws IOException //from www.j a v a 2 s. c o m * */ private void doSearch() throws IOException { final String CNT = "CNT"; UIFieldFormatterIFace fieldFmt = null; if (typeCBX.getSelectedIndex() == 0) { fieldFmt = DBTableIdMgr.getFieldFormatterFor(CollectionObject.class, "catalogNumber"); } final StringBuilder pmStr = new StringBuilder(); final String placeMark = " <Placemark><name>%s - %d / %d</name><Point><coordinates>%8.5f, %8.5f, 5</coordinates></Point></Placemark>\n"; polySB.setLength(0); boxSB.setLength(0); final JStatusBar statusBar = UIRegistry.getStatusBar(); final UIFieldFormatterIFace fldFmt = fieldFmt; SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() { @Override protected Integer doInBackground() throws Exception { // fills pntList from polyline // polyline was filled via clicks on WorldWind totalNumRecords = BasicSQLUtils.getCountAsInt(buildSQL(true)); availPoints.clear(); model = (DefaultListModel) dbObjList.getModel(); model.removeAllElements(); topIdHash.clear(); markers.clear(); polygon = new Polyline(polyline.getPositions()); polygon.setClosed(true); for (Position p : polyline.getPositions()) { polySB.append(String.format(" %8.5f, %8.5f, 20\n", p.longitude.degrees, p.latitude.degrees)); } int maxThreshold = 1000; int index = 0; Connection conn = null; Statement stmt = null; try { conn = DBConnection.getInstance().createConnection(); stmt = conn.createStatement(); int currCnt = 0; ResultSet rs = stmt.executeQuery(buildSQL(false)); while (rs.next()) { if (currCnt < maxThreshold) { double lat = rs.getBigDecimal(2).doubleValue(); double lon = rs.getBigDecimal(3).doubleValue(); Position pos = Position.fromDegrees(lat, lon, 0.0); // ZZZ // if (GeometryMath.isLocationInside(pos, polygon.getPositions())) // { // LatLonPoint llp = new LatLonPoint(rs.getInt(1), lat, lon); // String title = rs.getString(4); // if (title != null) // { // title = (fldFmt != null ? fldFmt.formatToUI(title) :title).toString(); // } else // { // title = "N/A"; // } // llp.setTitle(title); // llp.setIndex(index++); // availPoints.add(llp); // markers.add(llp); // topIdHash.add(llp.getLocId()); // System.out.println(index+" / "+currCnt+" In: "+lat+", "+lon); // pmStr.append(String.format(placeMark, "In: ",index, currCnt, lon, lat)); // // } else // { // System.out.println(index+" / "+currCnt+" Tossing: "+lat+", "+lon); // pmStr.append(String.format(placeMark, "Tossing: ", index, currCnt, lon, lat)); // } } currCnt++; if (currCnt % 100 == 0) { firePropertyChange(CNT, 0, currCnt); } } rs.close(); } catch (SQLException ex) { ex.printStackTrace(); /*UsageTracker.incrSQLUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BaseTreeTask.class, ex); log.error("SQLException: " + ex.toString()); //$NON-NLS-1$ lo .error(ex.getMessage());*/ } finally { try { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BaseTreeTask.class, ex); ex.printStackTrace(); } } return null; } /* (non-Javadoc) * @see javax.swing.SwingWorker#done() */ @Override protected void done() { super.done(); if (doDebug) { try { final String template = FileUtils.readFileToString(new File("template.kml")); final PrintWriter pw = new PrintWriter(new File("debug.kml")); String str = StringUtils.replace(template, "<!-- BOX -->", boxSB.toString()); str = StringUtils.replace(str, "<!-- POLYGON -->", polySB.toString()); str = StringUtils.replace(str, "<!-- PLACEMARKS -->", pmStr.toString()); pw.println(str); pw.flush(); pw.close(); } catch (IOException ex) { } } UIRegistry.clearSimpleGlassPaneMsg(); statusBar.setProgressDone(STATUSBAR_NAME); for (LatLonPlacemarkIFace llp : markers) { model.addElement(llp); } if (markers.size() > 0) { wwPanel.placeMarkers(markers, null); searchBtn.setEnabled(false); } else { doClearAll(true); startBtn.setEnabled(false); } clearAllBtn.setEnabled(true); clearSearchBtn.setEnabled(true); } }; statusBar.setIndeterminate(STATUSBAR_NAME, false); statusBar.setProgressRange(STATUSBAR_NAME, 0, 100); final SimpleGlassPane glassPane = UIRegistry .writeSimpleGlassPaneMsg(getLocalizedMessage("MySQLBackupService.BACKINGUP", "XXX"), 24); worker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { if (CNT.equals(evt.getPropertyName())) { int value = (Integer) evt.getNewValue(); int progress = (int) (((double) value / (double) totalNumRecords) * 100.0); glassPane.setProgress(progress); statusBar.setValue(STATUSBAR_NAME, progress); } } }); worker.execute(); }
From source file:com.mirth.connect.client.ui.SettingsPanelServer.java
public void doClearAllStats() { String result = JOptionPane.showInputDialog(this, "<html>This will reset all channel statistics (including lifetime statistics) for<br>all channels (including undeployed channels).<br><font size='1'><br></font>Type CLEAR and click the OK button to continue.</html>", "Clear All Statistics", JOptionPane.WARNING_MESSAGE); if (result != null) { if (!result.equals("CLEAR")) { getFrame().alertWarning(SettingsPanelServer.this, "You must type CLEAR to clear all statistics."); return; }/* ww w.j a v a 2 s . c om*/ final String workingId = getFrame().startWorking("Clearing all statistics..."); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { private Exception exception = null; public Void doInBackground() { try { getFrame().mirthClient.clearAllStatistics(); } catch (ClientException e) { exception = e; getFrame().alertThrowable(SettingsPanelServer.this, e); } return null; } public void done() { getFrame().stopWorking(workingId); if (exception == null) { getFrame().alertInformation(SettingsPanelServer.this, "All current and lifetime statistics have been cleared for all channels."); } } }; worker.execute(); } }
From source file:es.emergya.ui.gis.popups.ConsultaHistoricos.java
private JButton getLimpiar() { JButton jButton = new JButton(LogicConstants.getIcon("button_limpiar")); jButton.setText("Limpiar"); jButton.addActionListener(new ActionListener() { @Override//from www .j ava 2s. co m public void actionPerformed(ActionEvent e) { SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() { @Override protected Object doInBackground() throws Exception { clearRecursos(); clearIncidencias(); cleanLayers(); if (visorHistorico != null) { visorHistorico.updateControls(); } return null; } @Override protected void done() { HistoryMapViewer.enableSaveGpx(false); HistoryMapViewer.getResultadoHistoricos().setSelected(false); recursos.setSelectedIndex(-1); incidencias.setSelectedIndex(-1); // zona.setSelectedIndex(-1); final Calendar instance = Calendar.getInstance(); calendarini.setDate(instance.getTime()); calendarfin.setDate(instance.getTime()); horafin.setValue(instance.getTime()); instance.set(Calendar.HOUR_OF_DAY, 0); instance.set(Calendar.MINUTE, 0); instance.set(Calendar.SECOND, 0); horaini.setValue(instance.getTime()); soloUltimas.setSelected(false); calendarini.setEnabled(true); calendarfin.setEnabled(true); horaini.setEnabled(true); horafin.setEnabled(true); consultar.setEnabled(false); limpiar.setEnabled(false); setError(""); } }; sw.execute(); } }); return jButton; }
From source file:sk.uniza.fri.pds.spotreba.energie.gui.MainGui.java
private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem6ActionPerformed new SwingWorker<List, RuntimeException>() { @Override/*from www .j av a 2s . c o m*/ protected List doInBackground() throws Exception { try { return SeZamestnanecService.getInstance().findBest(3); } catch (RuntimeException e) { publish(e); return null; } } @Override protected void done() { try { List data = get(); showJTable(ZamestnanecOdpisReport.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:es.emergya.ui.plugins.AdminPanel.java
/** * Cambia los datos que muestra la tabla al array que se le pase. * /*from w ww .j av a2s. c o m*/ * Se aconseja que sean: * {@link Boolean} para valores si/no * * {@link AbstractAction} o subclases para botones * Numeros * * {@link String} para todo lo demas * * @param data */ public void setTableData(final Object[][] data) { final Object[][] newData = new Object[data.length][]; SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() { private MyTableModel model; @Override protected Object doInBackground() throws Exception { if (data == null) { return null; } model = (MyTableModel) table.getModel(); synchronized (seleccion) { for (int i = 0; i < model.getRowCount(); i++) { if ((Boolean) model.getValueAt(i, 0)) { seleccion.add(model.getValueAt(i, columnToReselect)); } } } synchronized (seleccion) { for (int i = 0; i < data.length; i++) { newData[i] = new Object[data[0].length + 1]; newData[i][0] = new Boolean(Authentication.isAuthenticated() && seleccion.contains(data[i][columnToReselect - 1])); for (int j = 0; j < data[i].length; j++) { newData[i][j + 1] = data[i][j]; } } } return null; } protected void done() { model.updateRows(newData); if (!initialized) { table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); for (Integer i : colsWidth.keySet()) { try { final TableColumn column = table.getColumnModel().getColumn(i); final TableColumn filtro = filters.getColumnModel().getColumn(i); column.setPreferredWidth(colsWidth.get(i)); column.setMinWidth(colsWidth.get(i)); column.setMaxWidth(colsWidth.get(i)); filtro.setPreferredWidth(colsWidth.get(i)); filtro.setMinWidth(colsWidth.get(i)); filtro.setMaxWidth(colsWidth.get(i)); } catch (Throwable t) { log.error("Error al resizar las columnas: " + t); } } TableColumn col = table.getColumnModel().getColumn(0); TableColumn fil = filters.getColumnModel().getColumn(0); log.trace("Resizando CheckBox"); col.setMaxWidth(49); fil.setMaxWidth(49); int defaultWidth = 54; for (int i = 1; i < table.getColumnModel().getColumnCount() - 2; i++) { col = table.getColumnModel().getColumn(i); fil = filters.getColumnModel().getColumn(i); final Class<?> columnClass = ((MyTableModel) table.getModel()).getColumnClass(i); if (columnClass == JButton.class) { log.trace("Resizando JButton"); col.setMaxWidth(defaultWidth); fil.setMaxWidth(defaultWidth); } else if (columnClass == Boolean.class) { log.trace("Resizando CheckBox"); col.setMaxWidth(49); fil.setMaxWidth(49); } } if (getCanDelete()) { col = table.getColumnModel().getColumn(table.getColumnModel().getColumnCount() - 2); col.setMaxWidth(defaultWidth); col.setPreferredWidth(defaultWidth); col = table.getColumnModel().getColumn(table.getColumnModel().getColumnCount() - 1); col.setMaxWidth(defaultWidth); col.setPreferredWidth(defaultWidth); } else { col = table.getColumnModel().getColumn(table.getColumnModel().getColumnCount() - 1); col.setMaxWidth(defaultWidth * 2); col.setPreferredWidth(defaultWidth * 2); } int max = filters.getColumnModel().getColumnCount() - 1; filters.getColumnModel().getColumn(max).setMaxWidth(61); filters.getColumnModel().getColumn(max - 1).setMaxWidth(32); filters.getColumnModel().getColumn(max - 2).setMaxWidth(32); initialized = true; } } }; sw.execute(); }
From source file:com.mirth.connect.client.ui.LoginPanel.java
private void loginButtonActionPerformed(java.awt.event.ActionEvent evt)// GEN-FIRST:event_loginButtonActionPerformed {// GEN-HEADEREND:event_loginButtonActionPerformed errorPane.setVisible(false);/*w w w . j a va2 s . c o m*/ SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { public Void doInBackground() { boolean errorOccurred = false; try { String server = serverName.getText(); client = new Client(server, PlatformUI.HTTPS_PROTOCOLS, PlatformUI.HTTPS_CIPHER_SUITES); PlatformUI.SERVER_URL = server; // Attempt to login LoginStatus loginStatus = null; try { loginStatus = client.login(username.getText(), String.valueOf(password.getPassword())); } catch (ClientException ex) { ex.printStackTrace(); if (ex instanceof UnauthorizedException) { UnauthorizedException e2 = (UnauthorizedException) ex; if (e2.getResponse() != null && e2.getResponse() instanceof LoginStatus) { loginStatus = (LoginStatus) e2.getResponse(); } } // Leave loginStatus null, the error message will be set to the default } // If SUCCESS or SUCCESS_GRACE_PERIOD if ((loginStatus != null) && ((loginStatus.getStatus() == LoginStatus.Status.SUCCESS) || (loginStatus.getStatus() == LoginStatus.Status.SUCCESS_GRACE_PERIOD))) { try { String serverName = client.getServerSettings().getServerName(); if (!StringUtils.isBlank(serverName)) { PlatformUI.SERVER_NAME = serverName; } else { PlatformUI.SERVER_NAME = null; } } catch (ClientException e) { PlatformUI.SERVER_NAME = null; } try { String database = (String) client.getAbout().get("database"); if (!StringUtils.isBlank(database)) { PlatformUI.SERVER_DATABASE = database; } else { PlatformUI.SERVER_DATABASE = null; } } catch (ClientException e) { PlatformUI.SERVER_DATABASE = null; } try { Map<String, String[]> map = client.getProtocolsAndCipherSuites(); PlatformUI.SERVER_HTTPS_SUPPORTED_PROTOCOLS = map .get(MirthSSLUtil.KEY_SUPPORTED_PROTOCOLS); PlatformUI.SERVER_HTTPS_ENABLED_CLIENT_PROTOCOLS = map .get(MirthSSLUtil.KEY_ENABLED_CLIENT_PROTOCOLS); PlatformUI.SERVER_HTTPS_ENABLED_SERVER_PROTOCOLS = map .get(MirthSSLUtil.KEY_ENABLED_SERVER_PROTOCOLS); PlatformUI.SERVER_HTTPS_SUPPORTED_CIPHER_SUITES = map .get(MirthSSLUtil.KEY_SUPPORTED_CIPHER_SUITES); PlatformUI.SERVER_HTTPS_ENABLED_CIPHER_SUITES = map .get(MirthSSLUtil.KEY_ENABLED_CIPHER_SUITES); } catch (ClientException e) { } PlatformUI.USER_NAME = StringUtils.defaultString(loginStatus.getUpdatedUsername(), username.getText()); setStatus("Authenticated..."); new Mirth(client); LoginPanel.getInstance().setVisible(false); User currentUser = PlatformUI.MIRTH_FRAME.getCurrentUser(PlatformUI.MIRTH_FRAME); Properties userPreferences = new Properties(); Set<String> preferenceNames = new HashSet<String>(); preferenceNames.add("firstlogin"); preferenceNames.add("checkForNotifications"); preferenceNames.add("showNotificationPopup"); preferenceNames.add("archivedNotifications"); try { userPreferences = client.getUserPreferences(currentUser.getId(), preferenceNames); // Display registration dialog if it's the user's first time logging in String firstlogin = userPreferences.getProperty("firstlogin"); if (firstlogin == null || BooleanUtils.toBoolean(firstlogin)) { new FirstLoginDialog(currentUser); } else if (loginStatus.getStatus() == LoginStatus.Status.SUCCESS_GRACE_PERIOD) { new ChangePasswordDialog(currentUser, loginStatus.getMessage()); } // Check for new notifications from update server if enabled String checkForNotifications = userPreferences.getProperty("checkForNotifications"); if (checkForNotifications == null || BooleanUtils.toBoolean(checkForNotifications)) { Set<Integer> archivedNotifications = new HashSet<Integer>(); String archivedNotificationString = userPreferences .getProperty("archivedNotifications"); if (archivedNotificationString != null) { archivedNotifications = ObjectXMLSerializer.getInstance() .deserialize(archivedNotificationString, Set.class); } // Update the Other Tasks pane with the unarchived notification count int unarchivedNotifications = ConnectServiceUtil.getNotificationCount( PlatformUI.SERVER_ID, PlatformUI.SERVER_VERSION, LoadedExtensions.getInstance().getExtensionVersions(), archivedNotifications, PlatformUI.HTTPS_PROTOCOLS, PlatformUI.HTTPS_CIPHER_SUITES); PlatformUI.MIRTH_FRAME.updateNotificationTaskName(unarchivedNotifications); // Display notification dialog if enabled and if there are new notifications String showNotificationPopup = userPreferences.getProperty("showNotificationPopup"); if (showNotificationPopup == null || BooleanUtils.toBoolean(showNotificationPopup)) { if (unarchivedNotifications > 0) { new NotificationDialog(); } } } } catch (ClientException e) { PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, e); } PlatformUI.MIRTH_FRAME.sendUsageStatistics(); } else { errorOccurred = true; if (loginStatus != null) { errorTextArea.setText(loginStatus.getMessage()); } else { errorTextArea.setText(ERROR_MESSAGE); } } } catch (Throwable t) { errorOccurred = true; errorTextArea.setText(ERROR_MESSAGE); t.printStackTrace(); } if (errorOccurred) { errorPane.setVisible(true); loggingIn.setVisible(false); loginMain.setVisible(true); loginProgress.setIndeterminate(false); password.grabFocus(); } return null; } public void done() { } }; worker.execute(); loggingIn.setVisible(true); loginMain.setVisible(false); loginProgress.setIndeterminate(true); }
From source file:es.emergya.ui.plugins.admin.AdminLayers.java
protected SummaryAction getSummaryAction(final CapaInformacion capaInformacion) { SummaryAction action = new SummaryAction(capaInformacion) { private static final long serialVersionUID = -3691171434904452485L; @Override//from ww w .j ava 2s .c o m protected JFrame getSummaryDialog() { if (capaInformacion != null) { d = getDialog(capaInformacion, null, "", null, "image/png"); return d; } else { JDialog primera = getJDialog(); primera.setResizable(false); primera.setVisible(true); primera.setAlwaysOnTop(true); } return null; } private JDialog getJDialog() { final JDialog dialog = new JDialog(); dialog.setTitle(i18n.getString("admin.capas.nueva.titleBar")); dialog.setIconImage(getBasicWindow().getIconImage()); dialog.setLayout(new BorderLayout()); JPanel centro = new JPanel(new FlowLayout()); centro.setOpaque(false); JLabel label = new JLabel(i18n.getString("admin.capas.nueva.url")); final JTextField url = new JTextField(50); final JLabel icono = new JLabel(LogicConstants.getIcon("48x48_transparente")); label.setLabelFor(url); centro.add(label); centro.add(url); centro.add(icono); dialog.add(centro, BorderLayout.CENTER); JPanel pie = new JPanel(new FlowLayout(FlowLayout.TRAILING)); pie.setOpaque(false); final JButton siguiente = new JButton(i18n.getString("admin.capas.nueva.boton.siguiente"), LogicConstants.getIcon("button_next")); JButton cancelar = new JButton(i18n.getString("admin.capas.nueva.boton.cancelar"), LogicConstants.getIcon("button_cancel")); final SiguienteActionListener siguienteActionListener = new SiguienteActionListener(url, dialog, icono, siguiente); url.addActionListener(siguienteActionListener); siguiente.addActionListener(siguienteActionListener); cancelar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialog.dispose(); } }); pie.add(siguiente); pie.add(cancelar); dialog.add(pie, BorderLayout.SOUTH); dialog.getContentPane().setBackground(Color.WHITE); dialog.pack(); dialog.setLocationRelativeTo(null); return dialog; } private JFrame getDialog(final CapaInformacion c, final Capa[] left_items, final String service, final Map<String, Boolean> transparentes, final String png) { if (left_items != null && left_items.length == 0) { JOptionPane.showMessageDialog(AdminLayers.this, i18n.getString("admin.capas.nueva.error.noCapasEnServicio")); } else { final String label_cabecera = i18n.getString("admin.capas.nueva.nombreCapa"); final String label_pie = i18n.getString("admin.capas.nueva.infoAdicional"); final String centered_label = i18n.getString("admin.capas.nueva.origenDatos"); final String left_label = i18n.getString("admin.capas.nueva.subcapasDisponibles"); final String right_label; if (left_items != null) { right_label = i18n.getString("admin.capas.nueva.capasSeleccionadas"); } else { right_label = i18n.getString("admin.capas.ficha.capasSeleccionadas"); } final String tituloVentana, cabecera; if (c.getNombre() == null) { tituloVentana = i18n.getString("admin.capas.nueva.titulo.nuevaCapa"); cabecera = i18n.getString("admin.capas.nueva.cabecera.nuevaCapa"); } else { tituloVentana = i18n.getString("admin.capas.nueva.titulo.ficha"); cabecera = i18n.getString("admin.capas.nueva.cabecera.ficha"); } final Capa[] right_items = c.getCapas().toArray(new Capa[0]); final AdminPanel.SaveOrUpdateAction<CapaInformacion> guardar = layers.new SaveOrUpdateAction<CapaInformacion>( c) { private static final long serialVersionUID = 7447770296943341404L; @Override public void actionPerformed(ActionEvent e) { if (isNew && CapaConsultas.alreadyExists(textfieldCabecera.getText())) { JOptionPane.showMessageDialog(super.frame, i18n.getString("admin.capas.nueva.error.nombreCapaYaExiste")); } else if (textfieldCabecera.getText().isEmpty()) { JOptionPane.showMessageDialog(super.frame, i18n.getString("admin.capas.nueva.error.nombreCapaEnBlanco")); } else if (((DefaultListModel) right.getModel()).size() == 0) { JOptionPane.showMessageDialog(super.frame, i18n.getString("admin.capas.nueva.error.noCapasSeleccionadas")); } else if (cambios) { int i = JOptionPane.showConfirmDialog(super.frame, i18n.getString("admin.capas.nueva.confirmar.guardar.titulo"), i18n.getString("admin.capas.nueva.confirmar.boton.guardar"), JOptionPane.YES_NO_CANCEL_OPTION); if (i == JOptionPane.YES_OPTION) { if (original == null) { original = new CapaInformacion(); } original.setInfoAdicional(textfieldPie.getText()); original.setNombre(textfieldCabecera.getText()); original.setHabilitada(habilitado.isSelected()); original.setOpcional(comboTipoCapa.getSelectedIndex() != 0); boolean transparente = true; HashSet<Capa> capas = new HashSet<Capa>(); List<Capa> capasEnOrdenSeleccionado = new ArrayList<Capa>(); int indice = 0; for (Object c : ((DefaultListModel) right.getModel()).toArray()) { if (c instanceof Capa) { transparente = transparente && (transparentes != null && transparentes.get(((Capa) c).getNombre()) != null && transparentes.get(((Capa) c).getNombre())); capas.add((Capa) c); capasEnOrdenSeleccionado.add((Capa) c); ((Capa) c).setCapaInformacion(original); ((Capa) c).setOrden(indice++); // ((Capa) // c).setNombre(c.toString()); } } original.setCapas(capas); if (original.getId() == null) { String url = nombre.getText(); if (url.indexOf("?") > -1) { if (!url.endsWith("?")) { url += "&"; } } else { url += "?"; } url += "VERSION=" + version + "&REQUEST=GetMap&FORMAT=" + png + "&SERVICE=" + service + "&WIDTH={2}&HEIGHT={3}&BBOX={1}&SRS={0}"; // if (transparente) url += "&TRANSPARENT=TRUE"; url += "&LAYERS="; String estilos = ""; final String coma = "%2C"; if (capasEnOrdenSeleccionado.size() > 0) { for (Capa c : capasEnOrdenSeleccionado) { url += c.getTitulo().replaceAll(" ", "+") + coma; estilos += c.getEstilo() + coma; } estilos = estilos.substring(0, estilos.length() - coma.length()); estilos = estilos.replaceAll(" ", "+"); url = url.substring(0, url.length() - coma.length()); } url += "&STYLES=" + estilos; original.setUrl_visible(original.getUrl()); original.setUrl(url); } CapaInformacionAdmin.saveOrUpdate(original); cambios = false; layers.setTableData(getAll(new CapaInformacion())); closeFrame(); } else if (i == JOptionPane.NO_OPTION) { closeFrame(); } } else { closeFrame(); } } }; JFrame segunda = generateUrlDialog(label_cabecera, label_pie, centered_label, tituloVentana, left_items, right_items, left_label, right_label, guardar, LogicConstants.getIcon("tittleficha_icon_capa"), cabecera, c.getHabilitada(), c.getOpcional(), c.getUrl_visible()); segunda.setResizable(false); if (c != null) { textfieldCabecera.setText(c.getNombre()); textfieldPie.setText(c.getInfoAdicional()); nombre.setText(c.getUrl_visible()); nombre.setEditable(false); if (c.getHabilitada() == null) { c.setHabilitada(false); } habilitado.setSelected(c.getHabilitada()); if (c.isOpcional() != null && c.isOpcional()) { comboTipoCapa.setSelectedIndex(1); } else { comboTipoCapa.setSelectedIndex(0); } } if (c.getId() == null) { habilitado.setSelected(true); comboTipoCapa.setSelectedIndex(1); } habilitado.setEnabled(true); if (c == null || c.getId() == null) { textfieldCabecera.setEditable(true); } else { textfieldCabecera.setEditable(false); } cambios = false; segunda.pack(); segunda.setLocationRelativeTo(null); segunda.setVisible(true); return segunda; } return null; } class SiguienteActionListener implements ActionListener { private final JTextField url; private final JDialog dialog; private final JLabel icono; private final JButton siguiente; public SiguienteActionListener(JTextField url, JDialog dialog, JLabel icono, JButton siguiente) { this.url = url; this.dialog = dialog; this.icono = icono; this.siguiente = siguiente; } @Override public void actionPerformed(ActionEvent e) { final CapaInformacion ci = new CapaInformacion(); ci.setUrl(url.getText()); ci.setCapas(new HashSet<Capa>()); SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() { private List<Capa> res = new LinkedList<Capa>(); private String service = "WMS"; private String png = null; private Map<String, Boolean> transparentes = new HashMap<String, Boolean>(); private ArrayList<String> errorStack = new ArrayList<String>(); private Boolean goOn = true; @SuppressWarnings(value = "unchecked") @Override protected Object doInBackground() throws Exception { try { final String url2 = ci.getUrl(); WMSClient client = new WMSClient(url2); client.connect(new ICancellable() { @Override public boolean isCanceled() { return false; } @Override public Object getID() { return System.currentTimeMillis(); } }); version = client.getVersion(); for (final String s : client.getLayerNames()) { WMSLayer layer = client.getLayer(s); // this.service = // client.getServiceName(); final Vector allSrs = layer.getAllSrs(); boolean epsg = (allSrs != null) ? allSrs.contains("EPSG:4326") : false; final Vector formats = client.getFormats(); if (formats.contains("image/png")) { png = "image/png"; } else if (formats.contains("IMAGE/PNG")) { png = "IMAGE/PNG"; } else if (formats.contains("png")) { png = "png"; } else if (formats.contains("PNG")) { png = "PNG"; } boolean image = png != null; if (png == null) { png = "IMAGE/PNG"; } if (epsg && image) { boolean hasTransparency = layer.hasTransparency(); this.transparentes.put(s, hasTransparency); Capa capa = new Capa(); capa.setCapaInformacion(ci); if (layer.getStyles().size() > 0) { capa.setEstilo(((WMSStyle) layer.getStyles().get(0)).getName()); } capa.setNombre(layer.getTitle()); capa.setTitulo(s); res.add(capa); if (!hasTransparency) { errorStack.add(i18n.getString(Locale.ROOT, "admin.capas.nueva.error.capaNoTransparente", layer.getTitle())); } } else { String error = ""; // if (opaque) // error += "<li>Es opaca</li>"; if (!image) { error += i18n.getString("admin.capas.nueva.error.formatoPNG"); } if (!epsg) { error += i18n.getString("admin.capas.nueva.error.projeccion"); } final String cadena = i18n.getString(Locale.ROOT, "admin.capas.nueva.error.errorCapa", new Object[] { s, error }); errorStack.add(cadena); } } } catch (final Throwable t) { log.error("Error al parsear el WMS", t); goOn = false; icono.setIcon(LogicConstants.getIcon("48x48_transparente")); JOptionPane.showMessageDialog(dialog, i18n.getString("admin.capas.nueva.error.errorParseoWMS")); siguiente.setEnabled(true); } return null; } @Override protected void done() { super.done(); if (goOn) { dialog.dispose(); ci.setUrl_visible(ci.getUrl()); final JFrame frame = getDialog(ci, res.toArray(new Capa[0]), service, transparentes, png); if (!errorStack.isEmpty()) { String error = "<html>"; for (final String s : errorStack) { error += s + "<br/>"; } error += "</html>"; final String errorString = error; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(frame, errorString); } }); } } } }; sw.execute(); icono.setIcon(LogicConstants.getIcon("anim_conectando")); icono.repaint(); siguiente.setEnabled(false); } } }; return action; }
From source file:sk.uniza.fri.pds.spotreba.energie.gui.MainGui.java
private void jMenuItem7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem7ActionPerformed new SwingWorker<List, RuntimeException>() { @Override/* ww w .j ava 2 s . c o m*/ protected List doInBackground() throws Exception { try { return SeHistoriaService.getInstance().getProblematickeDOmacnosti(); } catch (RuntimeException e) { publish(e); return null; } } @Override protected void done() { try { List data = get(); showJTable(SpotrebaDomacnosti.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:au.org.ala.delta.intkey.model.IntkeyContext.java
/** * Read and execute the specified dataset startup file. This file may be * either a "webstart" file, or a file containing actual directives to * initialize the dataset./*from w w w .jav a 2s. c om*/ * * This method will block while the calling thread while the file is read, * the dataset is loaded, and other directives in the file are executed. * * @param datasetFileURL * The dataset initialization file * @return SwingWorker used to load the dataset in a separate thread - unit * tests need this so that they can block until the dataset is * loaded. */ public synchronized void newDataSetFile(final URL datasetFileURL) { Logger.log("Reading in directives from url: %s", datasetFileURL.toString()); // Close any dialogs that have been left open. IntKeyDialogController.closeWindows(); cleanupOldDataset(); initializeIdentification(); // Loading of a new dataset can take a long time and hence can lock up // the UI. If this method is called from the Swing Event Dispatch // Thread, load the // new dataset on a background thread using a SwingWorker. if (SwingUtilities.isEventDispatchThread()) { _appUI.displayBusyMessage(UIUtils.getResourceString("LoadingDataset.caption")); SwingWorker<Void, Void> startupWorker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { processStartupFile(datasetFileURL); return null; } @Override protected void done() { try { get(); if (_dataset.getHeading() != null) { appendToLog(_dataset.getHeadingWithoutFormatting()); } if (_dataset.getSubHeading() != null) { appendToLog(_dataset.getSubheadingWithoutFormatting()); } _appUI.handleNewDataset(_dataset); } catch (Exception ex) { Logger.error("Error reading dataset file", ex); _appUI.displayErrorMessage(UIUtils.getResourceString("ErrorReadingReadsetFile.error", datasetFileURL.toString(), ex.getMessage())); } finally { _appUI.removeBusyMessage(); } } }; startupWorker.execute(); } else { try { processStartupFile(datasetFileURL); if (_dataset.getHeading() != null) { appendToLog(_dataset.getHeadingWithoutFormatting()); } if (_dataset.getSubHeading() != null) { appendToLog(_dataset.getSubheadingWithoutFormatting()); } _appUI.handleNewDataset(_dataset); } catch (Exception ex) { Logger.error("Error reading dataset file", ex); _appUI.displayErrorMessage(UIUtils.getResourceString("ErrorReadingReadsetFile.error", datasetFileURL.toString(), ex.getMessage())); } } }
From source file:burlov.ultracipher.swing.SwingGuiApplication.java
protected void measurePerformance() { SwingWorker<Double, Object> task = new SwingWorker<Double, Object>() { @Override//from www . j av a 2 s . com protected Double doInBackground() throws Exception { Ultracipher.measurePerformance();// Warm up return Ultracipher.measurePerformance(); } }; WaitDialog dlg = new WaitDialog(getMainFrame(), "Measure performance", task, 0, 0); dlg.start(); try { JOptionPane.showMessageDialog(getMainFrame(), String.format("Performance index (bigger is better): %.3f", task.get())); } catch (Exception e) { e.printStackTrace(); showError(e); } }