Example usage for javax.swing JOptionPane NO_OPTION

List of usage examples for javax.swing JOptionPane NO_OPTION

Introduction

In this page you can find the example usage for javax.swing JOptionPane NO_OPTION.

Prototype

int NO_OPTION

To view the source code for javax.swing JOptionPane NO_OPTION.

Click Source Link

Document

Return value from class method if NO is chosen.

Usage

From source file:serial.ChartFromSerial.java

public void hardRefresh() {
    portNames = SerialPort.getCommPorts();
    while (portNames.length == 0) {
        buttonsOff();/*from  www. jav  a 2  s .c  o  m*/
        if (JOptionPane.showConfirmDialog(rootPane, "No connected devices found.\nWould you like to refresh?",
                "Could not connect to any devices.", JOptionPane.YES_NO_OPTION,
                JOptionPane.ERROR_MESSAGE) == JOptionPane.NO_OPTION) {
            return;
        } else {
            portNames = SerialPort.getCommPorts();
        }
    }
    portList_jCombo.removeAllItems();
    for (SerialPort portName : portNames) {
        portList_jCombo.addItem(portName.getSystemPortName());
    }
    defaultButtonStates();
    if (chosenPort != null) {
        chosenPort.closePort();
    }
}

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);/*from w  ww. ja v a 2  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:de.tor.tribes.ui.views.DSWorkbenchSOSRequestAnalyzer.java

private void copySelectionToClipboardAsBBCode() {
    HashMap<Tribe, SOSRequest> selectedRequests = new HashMap<>();
    List<DefenseInformation> selection = getSelectedRows();
    if (selection.isEmpty()) {
        showInfo("Keine SOS Anfragen eingelesen");
        return;/*from  w ww. j  ava2 s  .  c  om*/
    }

    for (DefenseInformation info : selection) {
        Tribe defender = info.getTarget().getTribe();
        SOSRequest request = selectedRequests.get(defender);
        if (request == null) {
            request = new SOSRequest(defender);
            selectedRequests.put(defender, request);
        }
        TargetInformation targetInfo = request.addTarget(info.getTarget());
        targetInfo.merge(info.getTargetInformation());
    }

    try {
        boolean extended = (JOptionPaneHelper.showQuestionConfirmBox(this,
                "Erweiterte BB-Codes verwenden (nur fr Forum und Notizen geeignet)?", "Erweiterter BB-Code",
                "Nein", "Ja") == JOptionPane.YES_OPTION);

        StringBuilder buffer = new StringBuilder();
        if (extended) {
            buffer.append("[u][size=12]SOS Anfragen[/size][/u]\n\n");
        } else {
            buffer.append("[u]SOS Anfragen[/u]\n\n");
        }

        List<SOSRequest> requests = new LinkedList<>();
        CollectionUtils.addAll(requests, selectedRequests.values());
        buffer.append(new SosListFormatter().formatElements(requests, extended));

        if (extended) {
            buffer.append("\n[size=8]Erstellt am ");
            buffer.append(
                    new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss").format(Calendar.getInstance().getTime()));
            buffer.append(" mit DS Workbench ");
            buffer.append(Constants.VERSION).append(Constants.VERSION_ADDITION + "[/size]\n");
        } else {
            buffer.append("\nErstellt am ");
            buffer.append(
                    new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss").format(Calendar.getInstance().getTime()));
            buffer.append(" mit DS Workbench ");
            buffer.append(Constants.VERSION).append(Constants.VERSION_ADDITION + "\n");
        }

        String b = buffer.toString();
        StringTokenizer t = new StringTokenizer(b, "[");
        int cnt = t.countTokens();
        if (cnt > 1000) {
            if (JOptionPaneHelper.showQuestionConfirmBox(this,
                    "Die momentan vorhandenen Anfragen bentigen mehr als 1000 BB-Codes\n"
                            + "und knnen daher im Spiel (Forum/IGM/Notizen) nicht auf einmal dargestellt werden.\nTrotzdem exportieren?",
                    "Zu viele BB-Codes", "Nein", "Ja") == JOptionPane.NO_OPTION) {
                return;
            }
        }

        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(b), null);
        showSuccess("Daten in Zwischenablage kopiert");
    } catch (Exception e) {
        logger.error("Failed to copy data to clipboard", e);
        showError("Fehler beim Kopieren in die Zwischenablage");
    }

}

From source file:ca.uhn.hl7v2.testpanel.controller.Controller.java

public void revertMessage(Hl7V2MessageCollection theMsg) {
    if (StringUtils.isBlank(theMsg.getSaveFileName())) {
        showDialogError("Message has not yet been saved");
        return;/*from  w w w . j av a  2 s.  c  om*/
    }

    File file = new File(theMsg.getSaveFileName());
    if (file.exists() == false || file.isDirectory() || !file.canRead()) {
        showDialogError("File \"" + theMsg.getSaveFileName() + "\" can not be read");
        return;
    }

    int revert = showDialogYesNo("Revert file to saved contents? You will lose all changes.");
    if (revert == JOptionPane.NO_OPTION) {
        return;
    }

    Charset charSet = theMsg.getSaveCharset();
    String contents;
    try {
        contents = FileUtils.readFile(file, charSet);
    } catch (IOException e) {
        ourLog.error("Failed to read from file " + file.getAbsolutePath(), e);
        showDialogError("Failed to read from file: " + e.getMessage());
        return;
    }

    theMsg.setSourceMessage(contents);

}

From source file:com.lottery.gui.MainLotteryForm.java

private void btnBuyTicketActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuyTicketActionPerformed
    if (StringUtils.isBlank(tfBuyerName.getText().trim())) {
        JOptionPane.showMessageDialog(this, "Buyer name is blank!");
        tfBuyerName.requestFocusInWindow();
        return;/*from  w w w  .ja v a 2  s . co m*/
    }

    if (StringUtils.isBlank(ftfBuyStartDate.getText().trim())) {
        JOptionPane.showMessageDialog(this, "Start date is invalid (dd/MM/yyyy)!");
        ftfBuyStartDate.requestFocusInWindow();
        return;
    }

    Date startDate = null;

    try {
        startDate = LotteryUtils.getDate(ftfBuyStartDate.getText().trim());
    } catch (ParseException ex) {
        JOptionPane.showMessageDialog(this, "Start date is invalid (dd/MM/yyyy)!");
        ftfBuyStartDate.requestFocusInWindow();
        LOGGER.error(ex);
        return;
    }

    Date targetDate = LotteryUtils.getTargetDate(startDate);

    Date today = new Date();
    if (today.after(startDate)) {
        JOptionPane.showMessageDialog(this, "Start date must be greater than today!");
        tfBuyerName.requestFocusInWindow();
        return;
    }

    int dialogResult = JOptionPane.showConfirmDialog(this,
            "Would You Like to generate ticket for: " + tfBuyerName.getText() + "?", "Warning",
            JOptionPane.YES_OPTION);
    if (dialogResult == JOptionPane.NO_OPTION) {
        return;
    }

    //        Date today = new Date();
    //        Date startDate = LotteryUtils.getNextDate(today);

    //        int startDay = LotteryUtils.getDayOfMonth(startDate);
    //        int maxDayOfMonth = LotteryUtils.getLastDayOfMonth(startDate);
    //
    //        buyerService.getAll();

    Buyer buyer = new Buyer();
    buyer.setName(tfBuyerName.getText().trim());
    buyer.setIc(tfBuyerIc.getText().trim());

    List<String> linesBallsDb = new ArrayList<>();
    List<Ticket> newTickets = new ArrayList<>();
    Date queryDate = startDate;

    int count = 0;
    try {
        //            for (int dayOfMonth = startDay; dayOfMonth <= maxDayOfMonth; dayOfMonth++) {
        for (; queryDate.before(targetDate);) {

            List<TicketTable> ticketTables = ticketTableService.getByDate(queryDate);
            linesBallsDb = LotteryUtils.getAllLinesBalls(ticketTables);
            Ticket newTicket = LotteryUtils.generateTicket(linesBallsDb, queryDate, count++);
            newTicket.setBuyer(buyer);
            newTickets.add(newTicket);
            queryDate = LotteryUtils.getNextDate(queryDate);

        }

        buyer.setTickets(newTickets);

        LotteryUtils.generatePhysicalTicket(buyer, System.currentTimeMillis() + "_" + buyer.getName() + ".xls");

        buyerService.saveOrUpdate(buyer);
        JOptionPane.showMessageDialog(this, "Generate ticket successfully for " + tfBuyerName.getText() + "!");

        btnResetActionPerformed(null);
    } catch (LotteryException ex) {
        LOGGER.error("Generate ticket exception: ", ex);
        JOptionPane.showMessageDialog(this, "Please help to try again!");
    } catch (Exception ex2) {
        LOGGER.error("Generate ticket exception: ", ex2);
        JOptionPane.showMessageDialog(this,
                "Something goes wrong! Please try again or report to administrator!");
    }

}

From source file:jeplus.JEPlusFrameMain.java

/**
 * Start batch operation/*from   w ww .  ja v  a2 s .c  o  m*/
 */
public void startBatchRunAll() {
    // Update display
    if (OutputPanel == null) {
        OutputPanel = new EPlusTextPanelOld("Output", EPlusTextPanel.VIEWER_MODE);
        int tabn = TpnEditors.getTabCount();
        this.TpnEditors.insertTab("Executing batch ...", null, OutputPanel, "This is the execution log.", tabn);
        TpnEditors.setSelectedIndex(tabn);
    } else {
        TpnEditors.setSelectedComponent(OutputPanel);
    }
    // Check batch size and exec agent's capacity
    if (BatchManager.getBatchInfo().getTotalNumberOfJobs() > BatchManager.getAgent().getQueueCapacity()) {
        // Project is too large
        StringBuilder buf = new StringBuilder("<html><p>The estimated batch size (");
        buf.append(LargeIntFormatter.format(BatchManager.getBatchInfo().getTotalNumberOfJobs()));
        buf.append(") exceeds the capacity of ").append(BatchManager.getAgent().getAgentID()).append(" (");
        buf.append(LargeIntFormatter.format(BatchManager.getAgent().getQueueCapacity()));
        buf.append(
                "). </p><p>A large batch may cause jEPlus to crash. Please choose a different agent, or use random sampling or optimisation.</p>");
        buf.append(
                "<p>However, the estimation did not take into account of manually fixed parameter values.</p><p>Please choose Yes if you want to go ahead with the simulation. </p>");
        int res = JOptionPane.showConfirmDialog(this, buf.toString(), "Batch is too large",
                JOptionPane.YES_NO_OPTION);
        if (res == JOptionPane.NO_OPTION) {
            OutputPanel.appendContent("Batch cancelled.\n");
            return;
        }
    }
    // Build jobs
    OutputPanel.appendContent("Building jobs ... ");
    ActingManager = BatchManager;
    // Start job
    ActingManager.runAll();
    OutputPanel.appendContent("" + ActingManager.getJobQueue().size() + " jobs created.\n");
    OutputPanel.appendContent("Starting simulation ...\n");
}

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  ww w .ja  va2  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:edu.ku.brc.specify.tools.ireportspecify.MainFrameSpecify.java

/**
 * @param appResName/*from   w  w  w .j  a  va  2s . c om*/
 * @param tableid
 * @return AppResource with the provided name.
 * 
 * If a resource named appResName exists it will be returned, else a new resource is created.
 */
private static AppResAndProps getAppRes(final String appResName, final Integer tableid,
        final boolean confirmOverwrite) {
    AppResourceIFace resApp = AppContextMgr.getInstance().getResource(appResName);
    if (resApp != null) {
        if (!confirmOverwrite) {
            return new AppResAndProps(resApp, null);
        }
        //else
        int option = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(),
                String.format(UIRegistry.getResourceString("REP_CONFIRM_IMP_OVERWRITE"), resApp.getName()),
                UIRegistry.getResourceString("REP_CONFIRM_IMP_OVERWRITE_TITLE"), JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE, null, null, JOptionPane.NO_OPTION);

        if (option == JOptionPane.YES_OPTION) {
            return new AppResAndProps(resApp, null);
        }
        //else
        return null;
    }
    //else
    return createAppResAndProps(appResName, tableid, null);
}

From source file:ca.uhn.hl7v2.testpanel.controller.Controller.java

public boolean saveAllMessagesAndReturnFalseIfCancelIsPressed() {

    for (Hl7V2MessageCollection next : myMessagesList.getMessages()) {
        if (next.isSaved() == false) {
            int save = showPromptToSaveMessageBeforeClosingIt(next, true);
            switch (save) {
            case JOptionPane.YES_OPTION:
                if (!saveMessages(next)) {
                    return false;
                }/*from   w w w. j  a  v  a  2  s  .c  om*/
                break;
            case JOptionPane.NO_OPTION:
                break;
            case JOptionPane.CANCEL_OPTION:
                return false;
            default:
                // shouldn't happen
                throw new Error("invalid option:" + save);
            }
        }
    }

    return true;
}

From source file:edu.ku.brc.af.ui.forms.formatters.UIFormatterEditorDlg.java

@Override
protected void okButtonPressed() {
    if (fieldsPanel.getEditBtn().isEnabled()) {
        int userChoice = JOptionPane.NO_OPTION;
        Object[] options = { getResourceString("Continue"), //$NON-NLS-1$
                getResourceString("CANCEL") //$NON-NLS-1$
        };//from  w  w  w.j  a  v  a  2  s .com
        loadAndPushResourceBundle("masterusrpwd");

        userChoice = JOptionPane.showOptionDialog(this, getResourceString("UIFEDlg.ITEM_CHG"), //$NON-NLS-1$
                getResourceString("UIFEDlg.CHG_TITLE"), //$NON-NLS-1$
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
        if (userChoice == JOptionPane.NO_OPTION) {
            return;
        }
    }
    super.okButtonPressed();
    getDataFromUI();
}