List of usage examples for javax.swing JOptionPane YES_NO_OPTION
int YES_NO_OPTION
To view the source code for javax.swing JOptionPane YES_NO_OPTION.
Click Source Link
showConfirmDialog
. From source file:net.sf.jabref.gui.BasePanel.java
private void setupActions() { SaveDatabaseAction saveAction = new SaveDatabaseAction(this); CleanupAction cleanUpAction = new CleanupAction(this, Globals.prefs); actions.put(Actions.UNDO, undoAction); actions.put(Actions.REDO, redoAction); actions.put(Actions.FOCUS_TABLE, (BaseAction) () -> new FocusRequester(mainTable)); // The action for opening an entry editor. actions.put(Actions.EDIT, (BaseAction) selectionListener::editSignalled); // The action for saving a database. actions.put(Actions.SAVE, saveAction); actions.put(Actions.SAVE_AS, (BaseAction) saveAction::saveAs); actions.put(Actions.SAVE_SELECTED_AS, new SaveSelectedAction(SavePreferences.DatabaseSaveType.ALL)); actions.put(Actions.SAVE_SELECTED_AS_PLAIN, new SaveSelectedAction(SavePreferences.DatabaseSaveType.PLAIN_BIBTEX)); // The action for copying selected entries. actions.put(Actions.COPY, (BaseAction) () -> copy()); //when you modify this action be sure to adjust Actions.DELETE //they are the same except of the Localization, delete confirmation and Actions.COPY call actions.put(Actions.CUT, (BaseAction) () -> { runCommand(Actions.COPY);//w w w . java2 s .co m List<BibEntry> entries = mainTable.getSelectedEntries(); if (entries.isEmpty()) { return; } NamedCompound compound = new NamedCompound( (entries.size() > 1 ? Localization.lang("cut entries") : Localization.lang("cut entry"))); for (BibEntry entry : entries) { compound.addEdit(new UndoableRemoveEntry(database, entry, BasePanel.this)); database.removeEntry(entry); ensureNotShowingBottomPanel(entry); } compound.end(); getUndoManager().addEdit(compound); frame.output(formatOutputMessage(Localization.lang("Cut"), entries.size())); markBaseChanged(); }); //when you modify this action be sure to adjust Actions.CUT, //they are the same except of the Localization, delete confirmation and Actions.COPY call actions.put(Actions.DELETE, (BaseAction) () -> delete()); // The action for pasting entries or cell contents. // - more robust detection of available content flavors (doesn't only look at first one offered) // - support for parsing string-flavor clipboard contents which are bibtex entries. // This allows you to (a) paste entire bibtex entries from a text editor, web browser, etc // (b) copy and paste entries between multiple instances of JabRef (since // only the text representation seems to get as far as the X clipboard, at least on my system) actions.put(Actions.PASTE, (BaseAction) () -> paste()); actions.put(Actions.SELECT_ALL, (BaseAction) mainTable::selectAll); // The action for opening the preamble editor actions.put(Actions.EDIT_PREAMBLE, (BaseAction) () -> { if (preambleEditor == null) { PreambleEditor form = new PreambleEditor(frame, BasePanel.this, database); form.setLocationRelativeTo(frame); form.setVisible(true); preambleEditor = form; } else { preambleEditor.setVisible(true); } }); // The action for opening the string editor actions.put(Actions.EDIT_STRINGS, (BaseAction) () -> { if (stringDialog == null) { StringDialog form = new StringDialog(frame, BasePanel.this, database); form.setVisible(true); stringDialog = form; } else { stringDialog.setVisible(true); } }); // The action for toggling the groups interface actions.put(Actions.TOGGLE_GROUPS, (BaseAction) () -> { sidePaneManager.toggle("groups"); frame.groupToggle.setSelected(sidePaneManager.isComponentVisible("groups")); }); // action for collecting database strings from user actions.put(Actions.DB_CONNECT, new DbConnectAction(this)); // action for exporting database to external SQL database actions.put(Actions.DB_EXPORT, new AbstractWorker() { String errorMessage = ""; boolean connectedToDB; // run first, in EDT: @Override public void init() { DBStrings dbs = bibDatabaseContext.getMetaData().getDBStrings(); // get DBStrings from user if necessary if (dbs.isConfigValid()) { connectedToDB = true; } else { // init DB strings if necessary if (!dbs.isInitialized()) { dbs.initialize(); } // show connection dialog DBConnectDialog dbd = new DBConnectDialog(frame(), dbs); dbd.setLocationRelativeTo(BasePanel.this); dbd.setVisible(true); connectedToDB = dbd.isConnectedToDB(); // store database strings if (connectedToDB) { dbs = dbd.getDBStrings(); bibDatabaseContext.getMetaData().setDBStrings(dbs); dbd.dispose(); } } } // run second, on a different thread: @Override public void run() { if (!connectedToDB) { return; } final DBStrings dbs = bibDatabaseContext.getMetaData().getDBStrings(); try { frame.output(Localization.lang("Attempting SQL export...")); final DBExporterAndImporterFactory factory = new DBExporterAndImporterFactory(); final DatabaseExporter exporter = factory.getExporter(dbs.getDbPreferences().getServerType()); exporter.exportDatabaseToDBMS(bibDatabaseContext, getDatabase().getEntries(), dbs, frame); dbs.isConfigValid(true); } catch (Exception ex) { final String preamble = Localization .lang("Could not export to SQL database for the following reason:"); errorMessage = SQLUtil.getExceptionMessage(ex); LOGGER.info("Could not export to SQL database", ex); dbs.isConfigValid(false); JOptionPane.showMessageDialog(frame, preamble + '\n' + errorMessage, Localization.lang("Export to SQL database"), JOptionPane.ERROR_MESSAGE); } bibDatabaseContext.getMetaData().setDBStrings(dbs); } // run third, on EDT: @Override public void update() { // if no error, report success if (errorMessage.isEmpty()) { if (connectedToDB) { final DBStrings dbs = bibDatabaseContext.getMetaData().getDBStrings(); frame.output(Localization.lang("%0 export successful", dbs.getDbPreferences().getServerType().getFormattedName())); } } else { // show an error dialog if an error occurred final String preamble = Localization .lang("Could not export to SQL database for the following reason:"); frame.output(preamble + " " + errorMessage); JOptionPane.showMessageDialog(frame, preamble + '\n' + errorMessage, Localization.lang("Export to SQL database"), JOptionPane.ERROR_MESSAGE); errorMessage = ""; } } }); actions.put(FindUnlinkedFilesDialog.ACTION_COMMAND, (BaseAction) () -> { final FindUnlinkedFilesDialog dialog = new FindUnlinkedFilesDialog(frame, frame, BasePanel.this); dialog.setLocationRelativeTo(frame); dialog.setVisible(true); }); // The action for auto-generating keys. actions.put(Actions.MAKE_KEY, new AbstractWorker() { List<BibEntry> entries; int numSelected; boolean canceled; // Run first, in EDT: @Override public void init() { entries = getSelectedEntries(); numSelected = entries.size(); if (entries.isEmpty()) { // None selected. Inform the user to select entries first. JOptionPane.showMessageDialog(frame, Localization.lang("First select the entries you want keys to be generated for."), Localization.lang("Autogenerate BibTeX keys"), JOptionPane.INFORMATION_MESSAGE); return; } frame.block(); output(formatOutputMessage(Localization.lang("Generating BibTeX key for"), numSelected)); } // Run second, on a different thread: @Override public void run() { BibEntry bes; // First check if any entries have keys set already. If so, possibly remove // them from consideration, or warn about overwriting keys. // This is a partial clone of net.sf.jabref.gui.entryeditor.EntryEditor.GenerateKeyAction.actionPerformed(ActionEvent) for (final Iterator<BibEntry> i = entries.iterator(); i.hasNext();) { bes = i.next(); if (bes.getCiteKey() != null) { if (Globals.prefs.getBoolean(JabRefPreferences.AVOID_OVERWRITING_KEY)) { // Remove the entry, because its key is already set: i.remove(); } else if (Globals.prefs.getBoolean(JabRefPreferences.WARN_BEFORE_OVERWRITING_KEY)) { // Ask if the user wants to cancel the operation: CheckBoxMessage cbm = new CheckBoxMessage( Localization.lang("One or more keys will be overwritten. Continue?"), Localization.lang("Disable this confirmation dialog"), false); final int answer = JOptionPane.showConfirmDialog(frame, cbm, Localization.lang("Overwrite keys"), JOptionPane.YES_NO_OPTION); if (cbm.isSelected()) { Globals.prefs.putBoolean(JabRefPreferences.WARN_BEFORE_OVERWRITING_KEY, false); } if (answer == JOptionPane.NO_OPTION) { // Ok, break off the operation. canceled = true; return; } // No need to check more entries, because the user has already confirmed // that it's ok to overwrite keys: break; } } } Map<BibEntry, Object> oldvals = new HashMap<>(); // Iterate again, removing already set keys. This is skipped if overwriting // is disabled, since all entries with keys set will have been removed. if (!Globals.prefs.getBoolean(JabRefPreferences.AVOID_OVERWRITING_KEY)) { for (BibEntry entry : entries) { bes = entry; // Store the old value: oldvals.put(bes, bes.getCiteKey()); database.setCiteKeyForEntry(bes, null); } } final NamedCompound ce = new NamedCompound(Localization.lang("Autogenerate BibTeX keys")); // Finally, set the new keys: for (BibEntry entry : entries) { bes = entry; LabelPatternUtil.makeLabel(bibDatabaseContext.getMetaData(), database, bes, Globals.prefs); ce.addEdit(new UndoableKeyChange(database, bes, (String) oldvals.get(bes), bes.getCiteKey())); } ce.end(); getUndoManager().addEdit(ce); } // Run third, on EDT: @Override public void update() { if (canceled) { frame.unblock(); return; } markBaseChanged(); numSelected = entries.size(); //////////////////////////////////////////////////////////////////////////////// // Prevent selection loss for autogenerated BibTeX-Keys //////////////////////////////////////////////////////////////////////////////// for (final BibEntry bibEntry : entries) { SwingUtilities.invokeLater(() -> { final int row = mainTable.findEntry(bibEntry); if ((row >= 0) && (mainTable.getSelectedRowCount() < entries.size())) { mainTable.addRowSelectionInterval(row, row); } }); } //////////////////////////////////////////////////////////////////////////////// output(formatOutputMessage(Localization.lang("Generated BibTeX key for"), numSelected)); frame.unblock(); } }); // The action for cleaning up entry. actions.put(Actions.CLEANUP, cleanUpAction); actions.put(Actions.MERGE_ENTRIES, (BaseAction) () -> new MergeEntriesDialog(BasePanel.this)); actions.put(Actions.SEARCH, (BaseAction) searchBar::focus); // The action for copying the selected entry's key. actions.put(Actions.COPY_KEY, (BaseAction) () -> copyKey()); // The action for copying a cite for the selected entry. actions.put(Actions.COPY_CITE_KEY, (BaseAction) () -> copyCiteKey()); // The action for copying the BibTeX key and the title for the first selected entry actions.put(Actions.COPY_KEY_AND_TITLE, (BaseAction) () -> copyKeyAndTitle()); actions.put(Actions.MERGE_DATABASE, new AppendDatabaseAction(frame, this)); actions.put(Actions.ADD_FILE_LINK, new AttachFileAction(this)); actions.put(Actions.OPEN_EXTERNAL_FILE, (BaseAction) () -> openExternalFile()); actions.put(Actions.OPEN_FOLDER, (BaseAction) () -> JabRefExecutorService.INSTANCE.execute(() -> { final List<File> files = FileUtil.getListOfLinkedFiles(mainTable.getSelectedEntries(), bibDatabaseContext.getFileDirectory()); for (final File f : files) { try { JabRefDesktop.openFolderAndSelectFile(f.getAbsolutePath()); } catch (IOException e) { LOGGER.info("Could not open folder", e); } } })); actions.put(Actions.OPEN_CONSOLE, (BaseAction) () -> JabRefDesktop .openConsole(frame.getCurrentBasePanel().getBibDatabaseContext().getDatabaseFile())); actions.put(Actions.OPEN_URL, new OpenURLAction()); actions.put(Actions.MERGE_DOI, (BaseAction) () -> new MergeEntryDOIDialog(BasePanel.this)); actions.put(Actions.REPLACE_ALL, (BaseAction) () -> { final ReplaceStringDialog rsd = new ReplaceStringDialog(frame); rsd.setVisible(true); if (!rsd.okPressed()) { return; } int counter = 0; final NamedCompound ce = new NamedCompound(Localization.lang("Replace string")); if (rsd.selOnly()) { for (BibEntry be : mainTable.getSelectedEntries()) { counter += rsd.replace(be, ce); } } else { for (BibEntry entry : database.getEntries()) { counter += rsd.replace(entry, ce); } } output(Localization.lang("Replaced") + ' ' + counter + ' ' + (counter == 1 ? Localization.lang("occurrence") : Localization.lang("occurrences")) + '.'); if (counter > 0) { ce.end(); getUndoManager().addEdit(ce); markBaseChanged(); } }); actions.put(Actions.DUPLI_CHECK, (BaseAction) () -> JabRefExecutorService.INSTANCE.execute(new DuplicateSearch(BasePanel.this))); actions.put(Actions.PLAIN_TEXT_IMPORT, (BaseAction) () -> { // get Type of new entry EntryTypeDialog etd = new EntryTypeDialog(frame); etd.setLocationRelativeTo(BasePanel.this); etd.setVisible(true); EntryType tp = etd.getChoice(); if (tp == null) { return; } String id = IdGenerator.next(); BibEntry bibEntry = new BibEntry(id, tp.getName()); TextInputDialog tidialog = new TextInputDialog(frame, bibEntry); tidialog.setLocationRelativeTo(BasePanel.this); tidialog.setVisible(true); if (tidialog.okPressed()) { UpdateField.setAutomaticFields(Collections.singletonList(bibEntry), false, false); insertEntry(bibEntry); } }); actions.put(Actions.MARK_ENTRIES, new MarkEntriesAction(frame, 0)); actions.put(Actions.UNMARK_ENTRIES, (BaseAction) () -> { try { List<BibEntry> bes = mainTable.getSelectedEntries(); if (bes.isEmpty()) { output(Localization.lang("This operation requires one or more entries to be selected.")); return; } NamedCompound ce = new NamedCompound(Localization.lang("Unmark entries")); for (BibEntry be : bes) { EntryMarker.unmarkEntry(be, false, database, ce); } ce.end(); getUndoManager().addEdit(ce); markBaseChanged(); String outputStr; if (bes.size() == 1) { outputStr = Localization.lang("Unmarked selected entry"); } else { outputStr = Localization.lang("Unmarked all %0 selected entries", Integer.toString(bes.size())); } output(outputStr); } catch (Throwable ex) { LOGGER.warn("Could not unmark", ex); } }); actions.put(Actions.UNMARK_ALL, (BaseAction) () -> { NamedCompound ce = new NamedCompound(Localization.lang("Unmark all")); for (BibEntry be : database.getEntries()) { EntryMarker.unmarkEntry(be, false, database, ce); } ce.end(); getUndoManager().addEdit(ce); markBaseChanged(); output(Localization.lang("Unmarked all entries")); }); // Note that we can't put the number of entries that have been reverted into the undoText as the concrete number cannot be injected actions.put(Relevance.getInstance().getValues().get(0).getActionName(), new SpecialFieldAction(frame, Relevance.getInstance(), Relevance.getInstance().getValues().get(0).getFieldValue().get(), true, Localization.lang("Toggle relevance"))); actions.put(Quality.getInstance().getValues().get(0).getActionName(), new SpecialFieldAction(frame, Quality.getInstance(), Quality.getInstance().getValues().get(0).getFieldValue().get(), true, Localization.lang("Toggle quality assured"))); actions.put(Printed.getInstance().getValues().get(0).getActionName(), new SpecialFieldAction(frame, Printed.getInstance(), Printed.getInstance().getValues().get(0).getFieldValue().get(), true, Localization.lang("Toggle print status"))); for (SpecialFieldValue prio : Priority.getInstance().getValues()) { actions.put(prio.getActionName(), prio.getAction(this.frame)); } for (SpecialFieldValue rank : Rank.getInstance().getValues()) { actions.put(rank.getActionName(), rank.getAction(this.frame)); } for (SpecialFieldValue status : ReadStatus.getInstance().getValues()) { actions.put(status.getActionName(), status.getAction(this.frame)); } actions.put(Actions.TOGGLE_PREVIEW, (BaseAction) () -> { boolean enabled = !Globals.prefs.getBoolean(JabRefPreferences.PREVIEW_ENABLED); Globals.prefs.putBoolean(JabRefPreferences.PREVIEW_ENABLED, enabled); setPreviewActiveBasePanels(enabled); frame.setPreviewToggle(enabled); }); actions.put(Actions.TOGGLE_HIGHLIGHTS_GROUPS_MATCHING_ANY, (BaseAction) () -> { new HighlightMatchingGroupPreferences(Globals.prefs).setToAny(); // ping the listener so it updates: groupsHighlightListener.listChanged(null); }); actions.put(Actions.TOGGLE_HIGHLIGHTS_GROUPS_MATCHING_ALL, (BaseAction) () -> { new HighlightMatchingGroupPreferences(Globals.prefs).setToAll(); // ping the listener so it updates: groupsHighlightListener.listChanged(null); }); actions.put(Actions.TOGGLE_HIGHLIGHTS_GROUPS_MATCHING_DISABLE, (BaseAction) () -> { new HighlightMatchingGroupPreferences(Globals.prefs).setToDisabled(); // ping the listener so it updates: groupsHighlightListener.listChanged(null); }); actions.put(Actions.SWITCH_PREVIEW, (BaseAction) selectionListener::switchPreview); actions.put(Actions.MANAGE_SELECTORS, (BaseAction) () -> { ContentSelectorDialog2 csd = new ContentSelectorDialog2(frame, frame, BasePanel.this, false, null); csd.setLocationRelativeTo(frame); csd.setVisible(true); }); actions.put(Actions.EXPORT_TO_CLIPBOARD, new ExportToClipboardAction(frame)); actions.put(Actions.SEND_AS_EMAIL, new SendAsEMailAction(frame)); actions.put(Actions.WRITE_XMP, new WriteXMPAction(this)); actions.put(Actions.ABBREVIATE_ISO, new AbbreviateAction(this, true)); actions.put(Actions.ABBREVIATE_MEDLINE, new AbbreviateAction(this, false)); actions.put(Actions.UNABBREVIATE, new UnabbreviateAction(this)); actions.put(Actions.AUTO_SET_FILE, new SynchronizeFileField(this)); actions.put(Actions.BACK, (BaseAction) BasePanel.this::back); actions.put(Actions.FORWARD, (BaseAction) BasePanel.this::forward); actions.put(Actions.RESOLVE_DUPLICATE_KEYS, new SearchFixDuplicateLabels(this)); actions.put(Actions.ADD_TO_GROUP, new GroupAddRemoveDialog(this, true, false)); actions.put(Actions.REMOVE_FROM_GROUP, new GroupAddRemoveDialog(this, false, false)); actions.put(Actions.MOVE_TO_GROUP, new GroupAddRemoveDialog(this, true, true)); actions.put(Actions.DOWNLOAD_FULL_TEXT, new FindFullTextAction(this)); }
From source file:at.tuwien.ifs.feature.evaluation.SimilarityRetrievalGUI.java
private JButton initButtonLoadClassInfo() { buttonLoadClassInfo = new JButton("Load class info file"); buttonLoadClassInfo.setEnabled(false); buttonLoadClassInfo.addActionListener(new ActionListener() { @Override//from w ww .j a v a 2s .co m public void actionPerformed(ActionEvent e) { fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.setFileFilter(new ExtensionFileFilterSwing(new String[] { "cls", "txt" })); if (fileChooser.getSelectedFile() != null) { // reusing the dialog fileChooser.setSelectedFile(null); } // TODO: remove fileChooser .setSelectedFile(new File("/data/music/ISMIRgenre/filelist_ISMIRgenre_mp3_wclasses.txt")); int returnVal = fileChooser.showDialog(SimilarityRetrievalGUI.this, "Open class information file"); if (returnVal == JFileChooser.APPROVE_OPTION) { try { SOMLibClassInformation clsInfo = new SOMLibClassInformation( fileChooser.getSelectedFile().getAbsolutePath()); // Sanity check if all the inputs are in the class info file String[] labels = inputData.get(0).getLabels(); ArrayList<String> missingLabels = new ArrayList<String>(); for (String label : labels) { if (!clsInfo.hasClassAssignmentForName(label)) { missingLabels.add(label); } } int answer = JOptionPane.YES_OPTION; if (missingLabels.size() > 0) { System.out.println(missingLabels); String missing = StringUtils.toString(missingLabels.toArray(), 5); answer = JOptionPane.showConfirmDialog(SimilarityRetrievalGUI.this, "Class information file '" + fileChooser.getSelectedFile().getAbsolutePath() + "' is missing the class assignment for " + missingLabels.size() + " vectors\n " + missing + "\nContinue loading?", "Missing class assignment", JOptionPane.YES_NO_OPTION); } if (missingLabels.size() == 0 || answer == JOptionPane.YES_OPTION) { classInfo = clsInfo; TableModel model = databaseDetailsTable.getModel(); for (int i = 0; i < labels.length; i++) { model.setValueAt(clsInfo.getClassName(labels[i]), i, 2); } resizeDatabaseDetailsTableColumns(); } } catch (SOMToolboxException e1) { JOptionPane.showMessageDialog(SimilarityRetrievalGUI.this, "Error loading class information file: " + e1.getMessage() + ". Aborting", "Error", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } } } }); return buttonLoadClassInfo; }
From source file:com.proyecto.vista.MantenimientoAmbiente.java
private void btnguardar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnguardar1ActionPerformed // TODO add your handling code here: List<Integer> array = new ArrayList(); array.add(FormularioUtil.Validar(FormularioUtil.TipoValidacion.NUMERO, this.nombreField, "Nombre")); array.add(FormularioUtil.Validar(FormularioUtil.TipoValidacion.NUMERO, this.empleadoField, "Responsable")); FormularioUtil.validar2(array);//w w w . j a v a2 s . com if (FormularioUtil.error) { JOptionPane.showMessageDialog(null, FormularioUtil.mensaje, "Mensaje del Sistema", JOptionPane.ERROR_MESSAGE); FormularioUtil.mensaje = ""; FormularioUtil.error = false; } else { String palabra = ""; String palabra2 = ""; if (accion == 1) { palabra = "registrar"; palabra2 = "registrado"; if (JOptionPane.showConfirmDialog(null, "Desea " + palabra + " el Ambiente?", "Mensaje del Sistema", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { ambienteControlador.getSeleccionado().setCodigo(idField.getText().toUpperCase()); ambienteControlador.getSeleccionado().setNombre(nombreField.getText().toUpperCase()); Area area = (Area) cmbArea.getSelectedItem(); ambienteControlador.getSeleccionado().setArea(area); ambienteControlador.accion(accion); lista.add(ambienteControlador.getSeleccionado()); if (accion == 1) { JOptionPane.showMessageDialog(null, "Ambiente " + palabra2 + " correctamente", "Mensaje del Sistema", JOptionPane.INFORMATION_MESSAGE); FormularioUtil.limpiarComponente(panelDatos); } else { JOptionPane.showMessageDialog(null, "Ambiente no " + palabra2, "Mensaje del Sistema", JOptionPane.ERROR_MESSAGE); } } else { FormularioUtil.limpiarComponente(panelDatos); JOptionPane.showMessageDialog(null, "Ambiente no " + palabra2, "Mensaje del Sistema", JOptionPane.ERROR_MESSAGE); } } else if (accion == 2) { palabra = "modificar"; palabra2 = "modificado"; if (JOptionPane.showConfirmDialog(null, "Desea " + palabra + " el Ambiente?", "Mensaje del Sistema", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { if (accion == 2) { JOptionPane.showMessageDialog(null, "Ambiente " + palabra2 + " correctamente", "Mensaje del Sistema", JOptionPane.INFORMATION_MESSAGE); lista.clear(); ambienteControlador.getSeleccionado().setCodigo(idField.getText().toUpperCase()); ambienteControlador.getSeleccionado().setNombre(nombreField.getText().toUpperCase()); Area area = (Area) cmbArea.getSelectedItem(); ambienteControlador.getSeleccionado().setArea(area); ambienteControlador.accion(accion); listar(); FormularioUtil.limpiarComponente(panelDatos); } else { JOptionPane.showMessageDialog(null, "Ambiente no " + palabra2, "Mensaje del Sistema", JOptionPane.ERROR_MESSAGE); } } else { FormularioUtil.limpiarComponente(panelDatos); JOptionPane.showMessageDialog(null, "Ambiente no " + palabra2, "Mensaje del Sistema", JOptionPane.ERROR_MESSAGE); } } FormularioUtil.activarComponente(panelOpciones, true); FormularioUtil.activarComponente(panelGuardar, false); FormularioUtil.activarComponente(panelDatos, false); } }
From source file:net.sf.jabref.EntryEditor.java
public boolean storeSource(boolean showError) { // Store edited bibtex code. BibtexParser bp = new BibtexParser(new StringReader(source.getText())); try {//w w w. jav a 2 s .c o m BibtexDatabase db = bp.parse().getDatabase(); if (db.getEntryCount() > 1) { throw new RuntimeException("More than one entry found."); } if (db.getEntryCount() < 1) { throw new RuntimeException("No entries found."); } BibtexEntry newEntry = db.getEntryById(db.getKeySet().iterator().next()); int id = entry.getId(); String newKey = newEntry.getCiteKey(); boolean hasChangesBetweenCurrentAndNew = false; boolean changedType = false; boolean duplicateWarning = false; boolean emptyWarning = StringUtils.isEmpty(newKey); if (panel.database.setCiteKeyForEntry(id, newKey)) { duplicateWarning = true; } NamedCompound compound = new NamedCompound(Globals.lang("source edit")); // First, remove fields that the user have removed (and add undo information to revert it if necessary) for (String fieldName : entry.getAllFields()) { String oldValue = entry.getField(fieldName); String newValue = newEntry.getField(fieldName); if (newValue == null) { compound.addEdit(new UndoableFieldChange(entry, fieldName, oldValue, null)); entry.clearField(fieldName); hasChangesBetweenCurrentAndNew = true; } } // Then set all fields that have been set by the user. for (String fieldName : newEntry.getAllFields()) { String oldValue = entry.getField(fieldName); String newValue = newEntry.getField(fieldName); if (newValue != null && !newValue.equals(oldValue)) { LatexFieldFormatter lff = new LatexFieldFormatter(); lff.format(newValue, fieldName); compound.addEdit(new UndoableFieldChange(entry, fieldName, oldValue, newValue)); entry.setField(fieldName, newValue); hasChangesBetweenCurrentAndNew = true; } } // See if the user has changed the entry type: if (newEntry.getType() != entry.getType()) { compound.addEdit(new UndoableChangeType(entry, entry.getType(), newEntry.getType())); entry.setType(newEntry.getType()); hasChangesBetweenCurrentAndNew = true; changedType = true; } compound.end(); if (!hasChangesBetweenCurrentAndNew) { return true; } panel.undoManager.addEdit(compound); if (duplicateWarning) { warnDuplicateBibtexkey(); } else if (emptyWarning && showError) { warnEmptyBibtexkey(); } else { panel.output(Globals.lang("Stored entry") + "."); } lastAcceptedSourceString = source.getText(); if (!changedType) { updateAllFields(); lastSourceAccepted = true; shouldUpdateSourcePanel = true; } else { panel.updateEntryEditorIfShowing(); // We will throw away the current EntryEditor, so we do not have to update it } // TODO: does updating work properly after source stored? // panel.tableModel.remap(); // panel.entryTable.repaint(); // panel.refreshTable(); panel.markBaseChanged(); SwingUtilities.invokeLater(new Runnable() { public void run() { final int row = panel.mainTable.findEntry(entry); if (row >= 0) { //if (panel.mainTable.getSelectedRowCount() == 0) // panel.mainTable.setRowSelectionInterval(row, row); //scrollTo(row); panel.mainTable.ensureVisible(row); } } }); return true; } catch (Throwable ex) { ex.printStackTrace(); // The source couldn't be parsed, so the user is given an // error message, and the choice to keep or revert the contents // of the source text field. shouldUpdateSourcePanel = false; lastSourceAccepted = false; tabbed.setSelectedComponent(srcPanel); if (showError) { Object[] options = { Globals.lang("Edit"), Globals.lang("Revert to original source") }; int answer = JOptionPane.showOptionDialog(frame, Globals.lang("Error") + ": " + ex.getMessage(), Globals.lang("Problem with parsing entry"), JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]); if (answer != 0) { shouldUpdateSourcePanel = true; updateSource(); } } return false; } }
From source file:UserInterface.FinanceRole.DonateToPoorPeopleJPanel.java
private void autoDonateJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_autoDonateJButtonActionPerformed objWorldEnterprise.getObjTransactionDirectory().updateTransactionAccount(); BigDecimal worldDonation = AutoDonate.donationCheck(objWorldEnterprise, objUserAccount); BigDecimal worldBalance = objWorldEnterprise.getObjTransactionDirectory().getAvailableVirtualBalance(); System.out.println(worldDonation); System.out.println(objWorldEnterprise.getObjTransactionDirectory().getAvailableRealBalance()); System.out.println(objWorldEnterprise.getObjTransactionDirectory().getAvailableVirtualBalance()); int positiveWorldBalance = worldBalance.compareTo(worldDonation); if (positiveWorldBalance >= 1) { //JDialog.setDefaultLookAndFeelDecorated(true); int response = JOptionPane.showConfirmDialog(null, "Total donation of $ " + worldDonation + "/- Do you want to Donate?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (response == JOptionPane.YES_OPTION) { System.out.println("Yes button clicked"); worldDonation = AutoDonate.donationConfirm(objWorldEnterprise, objUserAccount); JOptionPane.showMessageDialog(null, "$ " + worldDonation + "/- donated successfully"); }//from w ww .j a v a 2 s . c o m } else { JOptionPane.showMessageDialog(null, "World Balance is low"); } }
From source file:com.mirth.connect.client.ui.panels.connectors.PollingSettingsPanel.java
private void scheduleTypeActionPerformed() { String selectedType = (String) scheduleTypeComboBox.getSelectedItem(); // If connector is changing, ignore this... if (lastSelectedPollingType != null && channelContext && (!isDefaultProperties() || !cachedAdvancedConnectorProperties.equals(new PollConnectorPropertiesAdvanced()))) { if (!selectedType.equals(lastSelectedPollingType) && JOptionPane.showConfirmDialog( PlatformUI.MIRTH_FRAME,/* ww w. ja va 2 s . c om*/ "Are you sure you would like to change the polling type and lose all of the current properties?", "Select an Option", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { clearProperties(); enableComponents(selectedType); } else { scheduleTypeComboBox.setSelectedItem(lastSelectedPollingType); } } else { scheduleTypeComboBox.setSelectedItem(selectedType); enableComponents(selectedType); } updateNextFireTime(); }
From source file:jeplus.gui.JPanel_EPlusProjectFiles.java
private void cmdEditRVIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdEditRVIActionPerformed // Test if the template file is present String fn = (String) cboRviFile.getSelectedItem(); if (fn.startsWith("Select ")) { fn = "my.rvx"; }/*from w w w .jav a 2 s. co m*/ String templfn = RelativeDirUtil.checkAbsolutePath(txtRviDir.getText() + fn, Project.getBaseDir()); File ftmpl = new File(templfn); if (!ftmpl.exists()) { int n = JOptionPane.showConfirmDialog(this, "<html><p><center>" + templfn + " does not exist." + "Do you want to copy one from an existing file?</center></p>" + "<p> Alternatively, select 'NO' to create this file. </p>", "RVI file not available", JOptionPane.YES_NO_OPTION); if (n == JOptionPane.YES_OPTION) { // Select a file to open if (this.chkReadVar.isSelected()) { MainGUI.getFileChooser().setFileFilter(EPlusConfig.getFileFilter(EPlusConfig.RVX)); } else { MainGUI.getFileChooser().setFileFilter(EPlusConfig.getFileFilter(EPlusConfig.RVI)); } MainGUI.getFileChooser().setMultiSelectionEnabled(false); MainGUI.getFileChooser().setSelectedFile(new File("")); String rvidir = RelativeDirUtil.checkAbsolutePath(txtRviDir.getText(), Project.getBaseDir()); MainGUI.getFileChooser().setCurrentDirectory(new File(rvidir)); if (MainGUI.getFileChooser().showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { File file = MainGUI.getFileChooser().getSelectedFile(); try { FileUtils.copyFile(file, new File(templfn)); cboRviFile.setModel(new DefaultComboBoxModel(new String[] { fn })); Project.setRVIDir(txtRviDir.getText()); Project.setRVIFile(fn); } catch (IOException ex) { logger.error("Error copying RVX from source.", ex); } } MainGUI.getFileChooser().resetChoosableFileFilters(); MainGUI.getFileChooser().setSelectedFile(new File("")); } else if (n == JOptionPane.NO_OPTION) { } else { return; } } int idx = MainGUI.getTpnEditors().indexOfTab(fn); if (idx >= 0) { MainGUI.getTpnEditors().setSelectedIndex(idx); } else { EPlusEditorPanel RviFilePanel; if (FilenameUtils.getExtension(fn).equals("rvx")) { RviFilePanel = new EPlusEditorPanel(MainGUI.getTpnEditors(), fn, templfn, EPlusEditorPanel.FileType.RVX, null); } else { RviFilePanel = new EPlusEditorPanel(MainGUI.getTpnEditors(), fn, templfn, EPlusEditorPanel.FileType.RVI, null); } int ti = MainGUI.getTpnEditors().getTabCount(); MainGUI.getTpnEditors().addTab(fn, RviFilePanel); RviFilePanel.setTabId(ti); MainGUI.getTpnEditors().setSelectedIndex(ti); MainGUI.getTpnEditors().setTabComponentAt(ti, new ButtonTabComponent(MainGUI.getTpnEditors(), RviFilePanel)); MainGUI.getTpnEditors().setToolTipTextAt(ti, templfn); } }
From source file:fs.MainWindow.java
public void CrossValidation(int nr_executions, float percent_trainning, int selector) throws IOException { String penalization_type = (String) jCB_PenalizationCV.getSelectedItem(); float alpha = ((Double) jS_AlphaCV.getValue()).floatValue(); float q_entropy = ((Double) jS_QEntropyCV.getValue()).floatValue(); float beta = ((float) jSliderBetaCV.getValue() / 100); //if selected criterion function is CoD, q_entropy = 0 if (jCB_CriterionFunctionCV.getSelectedIndex() == 1) { q_entropy = 0;/*from www . j a v a 2s .c o m*/ } //CoD if (q_entropy < 0 || alpha < 0) { //entrada de dados invalida. JOptionPane.showMessageDialog(null, "Error on parameter value:" + "The values of q-entropy and Alpha must be positives.", "Application Error", JOptionPane.ERROR_MESSAGE); return; } dataset = new DefaultCategoryDataset(); double rate = 0; int n = Main.maximumValue(Md, 0, lines - 1, 0, columns - 2) + 1; int c = Main.maximumValue(Md, 0, lines - 1, columns - 1, columns - 1) + 1; jProgressBarCV.setValue(1); int total_samples = (int) (lines * percent_trainning); trainingset = new float[total_samples][columns]; testset = new float[lines - total_samples][columns]; //testset = new float[total_samples][columns]; char[][] strainingset = null; char[][] stestset = null; jProgressBarCV.setValue(3); float ex = (96 / nr_executions); /* calculating the estimated time to be completed in a computer of 2 GHz*/ int combinations = MathRoutines.numberCombinations(columns - 1, 1); double estimatedTime = (0.0062 + 3.2334e-7 * Mo.length) * combinations * Math.log(combinations) / Math.log(2); estimatedTime *= nr_executions; System.out.println("Estimated time to finish: " + estimatedTime + " s"); int answer = JOptionPane.showConfirmDialog(this, "Estimated time to finish: " + estimatedTime + " s.\n " + "Do you want to continue?", "Cross Validation", JOptionPane.YES_NO_OPTION); if (answer == 1) { jProgressBarCV.setValue(0); return; } //vetor com os resultados da selecao de caracteristica. int resultsetsize = 1; //vetor com os resultados da selecao de caracteristica. for (int executions = 0; executions < nr_executions; executions++) { if (flag_quantization) { Validation.GenerateSubSets(Md, percent_trainning, trainingset, testset); //Preprocessing.quantizecolumnsavg(trainingset, (Integer) jS_QuantizationValue.getValue(), true, has_labels); //Preprocessing.quantizecolumnsavg(testset, (Integer) jS_QuantizationValue.getValue(), false, has_labels); } else { Validation.GenerateSubSets(Mo, percent_trainning, trainingset, testset); } strainingset = MathRoutines.float2char(trainingset); stestset = MathRoutines.float2char(testset); int maxfeatures = (Integer) jS_MaxSetSizeCV.getValue(); if (maxfeatures <= 0) { JOptionPane .showMessageDialog( this, "Error on parameter value: The" + " Maximum Set Size be a integer value greater" + " or equal to 1.", "Application Error", JOptionPane.ERROR_MESSAGE); return; } FS fs = new FS(strainingset, n, c, penalization_type, alpha, beta, q_entropy, resultsetsize); if (selector == 1) { fs.runSFS(false, maxfeatures); } else if (selector == 3) { fs.runSFFS(maxfeatures, -1, null); } else if (selector == 2) { fs.runSFS(true, maxfeatures); /* a call to SFS is made in order to get the ideal dimension for the exhaustive search. */ int itmax = fs.itmax; FS fsPrev = new FS(strainingset, n, c, penalization_type, alpha, beta, q_entropy, resultsetsize); for (int i = 1; i <= itmax; i++) { fs = new FS(strainingset, n, c, penalization_type, alpha, beta, q_entropy, resultsetsize); fs.itmax = i; fs.runExhaustive(0, 0, fs.I); if (fs.hGlobal == 0) { break; } if (fs.hGlobal < fsPrev.hGlobal) { fsPrev = fs; } else { fs = fsPrev; break; } } } if (executions == 0) { jTA_SelectedFeaturesCV.setText("Execution " + (executions + 1) + " - Global Criterion Function Value: " + fs.hGlobal + "\n"); } else { jTA_SelectedFeaturesCV.append("\n\nExecution " + (executions + 1) + " - Global Criterion Function Value: " + fs.hGlobal + "\n"); } jTA_SelectedFeaturesCV.append("Selected Features: "); for (int i = 0; i < fs.I.size(); i++) { jTA_SelectedFeaturesCV.append(fs.I.elementAt(i) + " "); } jProgressBarCV.setValue(jProgressBarCV.getValue() + (int) (ex / 4)); Thread.yield(); /* CLASSIFICADOR. */ Classifier clas = new Classifier(); clas.classifierTable(strainingset, fs.I, n, c); jProgressBarCV.setValue(jProgressBarCV.getValue() + (int) (ex / 4)); Thread.yield(); for (int i = 0; i < clas.table.size(); i++) { double[] tableLine = (double[]) clas.table.elementAt(i); double instance = (Double) clas.instances.elementAt(i); System.out.print(instance + " "); for (int j = 0; j < c; j++) { System.out.print((int) tableLine[j] + " "); } System.out.println(); Thread.yield(); } //stestset = strainingset; double[] instances = clas.classifyTestSamples(stestset, fs.I, n, c); jProgressBarCV.setValue(jProgressBarCV.getValue() + (int) (ex / 4)); Thread.yield(); if (executions == 0) { jTA_SaidaCV.setText("Execution " + (executions + 1) + " - Correct Labels - Classified Labels - " + "Classification Instances\n"); } else { jTA_SaidaCV.append("\n\nExecution " + (executions + 1) + " - Correct Labels - Classified Labels - " + "Classification Instances\n"); } double hits = 0; for (int i = 0; i < clas.labels.length; i++) { //char correct_char = stestset[i].charAt(collumns-1); int correct_label = stestset[i][columns - 1]; //int correct_label = correct_char; int classified_label = clas.labels[i]; jTA_SaidaCV.append("\n" + correct_label + " - " + classified_label + " - " + instances[i]); if (correct_label == classified_label) { hits++; } } double hit_rate = hits / clas.labels.length; if (rate > 0) { rate = (rate + hit_rate) / 2; } else { rate = hit_rate; } jTA_SaidaCV.append("\nrate of hits = " + hit_rate); dataset.addValue(1 - rate, "Error Cross Validation", String.valueOf(executions + 1)); jProgressBarCV.setValue(jProgressBarCV.getValue() + (int) (ex / 4)); Thread.yield(); } Chart.LineChart(dataset, "Cross Validation Error with " + (int) (percent_trainning * 100) + "% of samples on Training Set", "Number of executions", "Mean Errors", false, 0, 0); jProgressBarCV.setValue(100); Thread.yield(); }
From source file:de.mendelson.comm.as2.client.AS2Gui.java
/** * Deletes the actual selected AS2 rows from the database, filesystem etc */// w w w . j av a 2s . com private void deleteSelectedMessages() { if (this.runtimeConnection == null) { return; } int requestValue = JOptionPane.showConfirmDialog(this, this.rb.getResourceString("dialog.msg.delete.message"), this.rb.getResourceString("dialog.msg.delete.title"), JOptionPane.YES_NO_OPTION); if (requestValue != JOptionPane.YES_OPTION) { return; } int[] selectedRows = this.jTableMessageOverview.getSelectedRows(); AS2Message[] overviewRows = ((TableModelMessageOverview) this.jTableMessageOverview.getModel()) .getRows(selectedRows); List<AS2MessageInfo> deleteList = new ArrayList<AS2MessageInfo>(); for (AS2Message message : overviewRows) { deleteList.add((AS2MessageInfo) message.getAS2Info()); } DeleteMessageRequest request = new DeleteMessageRequest(); request.setDeleteList(deleteList); this.getBaseClient().sendAsync(request); }
From source file:com.att.aro.ui.view.MainFrame.java
@Override public void updateCollectorStatus(CollectorStatus collectorStatus, StatusResult statusResult) { this.collectorStatus = collectorStatus; if (statusResult == null) { return;// ww w .jav a 2s . c o m } log.info("updateCollectorStatus :STATUS :" + statusResult); // timeout - collection not approved in time if (!statusResult.isSuccess()) { //String traceFolder = aroController.getTraceFolderPath(); log.info("updateCollectorStatus :FAILED STATUS :" + statusResult.getError().getDescription()); if (statusResult.getError().getCode() == 206) { int option = MessageDialogFactory.getInstance().showStopDialog(window.getJFrame(), statusResult.getError().getDescription(), BUNDLE.getString("error.title"), JOptionPane.DEFAULT_OPTION); if (option == JOptionPane.YES_NO_OPTION || CollectorStatus.CANCELLED == collectorStatus) { cancelCollector(); } } else { MessageDialogFactory.getInstance().showErrorDialog(window.getJFrame(), statusResult.getError().getDescription()); } return; } // Collection has been stopped ask to open trace if (collectorStatus != null && collectorStatus.equals(CollectorStatus.STOPPED)) { stopCollectorWorker.hideProgressDialog(); log.info("stopDialog"); String traceFolder = aroController.getTraceFolderPath(); int seconds = (int) (aroController.getTraceDuration() / 1000); boolean approveOpenTrace = MessageDialogFactory.getInstance().showTraceSummary( frmApplicationResourceOptimizer, traceFolder, !aroController.getVideoOption().equals(VideoOption.NONE), Util.formatHHMMSS(seconds)); if (approveOpenTrace) { updateTracePath(new File(aroController.getTraceFolderPath())); } return; } }