Example usage for javax.swing JOptionPane showConfirmDialog

List of usage examples for javax.swing JOptionPane showConfirmDialog

Introduction

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

Prototype

public static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType)
        throws HeadlessException 

Source Link

Document

Brings up a dialog where the number of choices is determined by the optionType parameter.

Usage

From source file:net.sf.jabref.gui.preftabs.PreferencesDialog.java

public PreferencesDialog(JabRefFrame parent) {
    super(parent, Localization.lang("JabRef preferences"), false);
    JabRefPreferences prefs = JabRefPreferences.getInstance();
    frame = parent;//from  w w w . j  a  v  a  2s  . c o  m

    main = new JPanel();
    JPanel mainPanel = new JPanel();
    JPanel lower = new JPanel();

    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(mainPanel, BorderLayout.CENTER);
    getContentPane().add(lower, BorderLayout.SOUTH);

    final CardLayout cardLayout = new CardLayout();
    main.setLayout(cardLayout);

    List<PrefsTab> tabs = new ArrayList<>();
    tabs.add(new GeneralTab(prefs));
    tabs.add(new NetworkTab(prefs));
    tabs.add(new FileTab(frame, prefs));
    tabs.add(new FileSortTab(prefs));
    tabs.add(new EntryEditorPrefsTab(frame, prefs));
    tabs.add(new GroupsPrefsTab(prefs));
    tabs.add(new AppearancePrefsTab(prefs));
    tabs.add(new ExternalTab(frame, this, prefs));
    tabs.add(new TablePrefsTab(prefs));
    tabs.add(new TableColumnsTab(prefs, parent));
    tabs.add(new LabelPatternPrefTab(prefs, parent.getCurrentBasePanel()));
    tabs.add(new PreviewPrefsTab(prefs));
    tabs.add(new NameFormatterTab(prefs));
    tabs.add(new ImportSettingsTab(prefs));
    tabs.add(new XmpPrefsTab(prefs));
    tabs.add(new AdvancedTab(prefs));

    // add all tabs
    tabs.forEach(tab -> main.add((Component) tab, tab.getTabName()));

    mainPanel.setBorder(BorderFactory.createEtchedBorder());

    String[] tabNames = tabs.stream().map(PrefsTab::getTabName).toArray(String[]::new);
    JList<String> chooser = new JList<>(tabNames);
    chooser.setBorder(BorderFactory.createEtchedBorder());
    // Set a prototype value to control the width of the list:
    chooser.setPrototypeCellValue("This should be wide enough");
    chooser.setSelectedIndex(0);
    chooser.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    // Add the selection listener that will show the correct panel when
    // selection changes:
    chooser.addListSelectionListener(e -> {
        if (e.getValueIsAdjusting()) {
            return;
        }
        String o = chooser.getSelectedValue();
        cardLayout.show(main, o);
    });

    JPanel buttons = new JPanel();
    buttons.setLayout(new GridLayout(4, 1));
    buttons.add(importPreferences, 0);
    buttons.add(exportPreferences, 1);
    buttons.add(showPreferences, 2);
    buttons.add(resetPreferences, 3);

    JPanel westPanel = new JPanel();
    westPanel.setLayout(new BorderLayout());
    westPanel.add(chooser, BorderLayout.CENTER);
    westPanel.add(buttons, BorderLayout.SOUTH);
    mainPanel.setLayout(new BorderLayout());
    mainPanel.add(main, BorderLayout.CENTER);
    mainPanel.add(westPanel, BorderLayout.WEST);

    JButton ok = new JButton(Localization.lang("OK"));
    JButton cancel = new JButton(Localization.lang("Cancel"));
    ok.addActionListener(new OkAction());
    CancelAction cancelAction = new CancelAction();
    cancel.addActionListener(cancelAction);
    lower.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
    ButtonBarBuilder buttonBarBuilder = new ButtonBarBuilder(lower);
    buttonBarBuilder.addGlue();
    buttonBarBuilder.addButton(ok);
    buttonBarBuilder.addButton(cancel);
    buttonBarBuilder.addGlue();

    // Key bindings:
    KeyBinder.bindCloseDialogKeyToCancelAction(this.getRootPane(), cancelAction);

    // Import and export actions:
    exportPreferences.setToolTipText(Localization.lang("Export preferences to file"));
    exportPreferences.addActionListener(e -> {
        String filename = FileDialogs.getNewFile(frame, new File(System.getProperty("user.home")),
                Collections.singletonList(".xml"), JFileChooser.SAVE_DIALOG, false);
        if (filename == null) {
            return;
        }
        File file = new File(filename);
        if (!file.exists() || (JOptionPane.showConfirmDialog(PreferencesDialog.this,
                Localization.lang("'%0' exists. Overwrite file?", file.getName()),
                Localization.lang("Export preferences"),
                JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION)) {

            try {
                prefs.exportPreferences(filename);
            } catch (JabRefException ex) {
                LOGGER.warn(ex.getMessage(), ex);
                JOptionPane.showMessageDialog(PreferencesDialog.this, ex.getLocalizedMessage(),
                        Localization.lang("Export preferences"), JOptionPane.ERROR_MESSAGE);
            }
        }
    });

    importPreferences.setToolTipText(Localization.lang("Import preferences from file"));
    importPreferences.addActionListener(e -> {
        String filename = FileDialogs.getNewFile(frame, new File(System.getProperty("user.home")),
                Collections.singletonList(".xml"), JFileChooser.OPEN_DIALOG, false);
        if (filename != null) {
            try {
                prefs.importPreferences(filename);
                updateAfterPreferenceChanges();
                JOptionPane.showMessageDialog(PreferencesDialog.this,
                        Localization.lang("You must restart JabRef for this to come into effect."),
                        Localization.lang("Import preferences"), JOptionPane.WARNING_MESSAGE);
            } catch (JabRefException ex) {
                LOGGER.warn(ex.getMessage(), ex);
                JOptionPane.showMessageDialog(PreferencesDialog.this, ex.getLocalizedMessage(),
                        Localization.lang("Import preferences"), JOptionPane.ERROR_MESSAGE);
            }
        }
    });

    showPreferences.addActionListener(
            e -> new PreferencesFilterDialog(new JabRefPreferencesFilter(Globals.prefs), frame)
                    .setVisible(true));
    resetPreferences.addActionListener(e -> {
        if (JOptionPane.showConfirmDialog(PreferencesDialog.this,
                Localization.lang("Are you sure you want to reset all settings to default values?"),
                Localization.lang("Reset preferences"),
                JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
            try {
                prefs.clear();
                JOptionPane.showMessageDialog(PreferencesDialog.this,
                        Localization.lang("You must restart JabRef for this to come into effect."),
                        Localization.lang("Reset preferences"), JOptionPane.WARNING_MESSAGE);
            } catch (BackingStoreException ex) {
                LOGGER.warn(ex.getMessage(), ex);
                JOptionPane.showMessageDialog(PreferencesDialog.this, ex.getLocalizedMessage(),
                        Localization.lang("Reset preferences"), JOptionPane.ERROR_MESSAGE);
            }
            updateAfterPreferenceChanges();
        }
    });

    setValues();

    pack();

}

From source file:com.seanmadden.net.fast.FastInterpretype.java

public void clearWindows() {
    boolean windowCleared = false;
    int selected = JOptionPane.showConfirmDialog(null,
            "Would you like to save the current conversation before clearing?", "Save before clearing?",
            JOptionPane.YES_NO_CANCEL_OPTION);
    if (selected == JOptionPane.YES_OPTION) {
        windowCleared = saveLogToFile();
    } else if (selected == JOptionPane.NO_OPTION) {
        windowCleared = true;//  www.j  ava 2  s. c  o  m
    }

    if (windowCleared) {
        si.sendRawDataToPort(DataPacket.generateClearConvoPayload());
        mw.clearWindow();
        String username = JOptionPane.showInputDialog("What is your name?");
        si.sendRawDataToPort(DataPacket.generateSignedOnPayload(username));
        mw.acceptText(username + " (you) has signed on.\n");
        mw.setLocalUserName(username);
    }
}

From source file:edu.mit.fss.examples.member.gui.PowerSubsystemPanel.java

/**
 * Export this panel's generation dataset.
 *//*from   w  ww.j  a va 2 s  .c om*/
private void exportDataset() {
    if (JFileChooser.APPROVE_OPTION == fileChooser.showSaveDialog(this)) {
        File f = fileChooser.getSelectedFile();

        if (!f.exists() || JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this,
                "Overwrite existing file " + f.getName() + "?", "File Exists", JOptionPane.YES_NO_OPTION)) {

            logger.info("Exporting dataset to file " + f.getPath() + ".");
            try {
                BufferedWriter bw = Files.newBufferedWriter(Paths.get(f.getPath()), Charset.defaultCharset());

                StringBuilder b = new StringBuilder();
                b.append(" Generation\n").append("Time, Value\n");
                for (int j = 0; j < generationSeries.getItemCount(); j++) {
                    b.append(generationSeries.getTimePeriod(j).getStart().getTime()).append(", ")
                            .append(generationSeries.getValue(j)).append("\n");
                }

                bw.write(b.toString());
                bw.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
    }
}

From source file:com.clank.launcher.swing.SwingHelper.java

/**
 * Asks the user a binary yes or no question.
 *
 * @param parentComponent the component// w w  w .ja  va 2  s  . c  o  m
 * @param message the message to display
 * @param title the title string for the dialog
 * @return whether 'yes' was selected
 */
public static boolean confirmDialog(final Component parentComponent, @NonNull final String message,
        @NonNull final String title) {
    if (SwingUtilities.isEventDispatchThread()) {
        return JOptionPane.showConfirmDialog(parentComponent, message, title,
                JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
    } else {
        // Use an AtomicBoolean to pass the result back from the
        // Event Dispatcher Thread
        final AtomicBoolean yesSelected = new AtomicBoolean();

        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    yesSelected.set(confirmDialog(parentComponent, title, message));
                }
            });
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }

        return yesSelected.get();
    }
}

From source file:net.sf.jabref.exporter.ExportFormats.java

/**
 * Create an AbstractAction for performing an export operation.
 *
 * @param frame//from www .  j a v a 2  s .  c  o  m
 *            The JabRefFrame of this JabRef instance.
 * @param selectedOnly
 *            true indicates that only selected entries should be exported,
 *            false indicates that all entries should be exported.
 * @return The action.
 */
public static AbstractAction getExportAction(JabRefFrame frame, boolean selectedOnly) {

    class ExportAction extends MnemonicAwareAction {

        private final JabRefFrame frame;

        private final boolean selectedOnly;

        public ExportAction(JabRefFrame frame, boolean selectedOnly) {
            this.frame = frame;
            this.selectedOnly = selectedOnly;
            putValue(Action.NAME, selectedOnly ? Localization.menuTitle("Export selected entries")
                    : Localization.menuTitle("Export"));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            ExportFormats.initAllExports();
            JFileChooser fc = ExportFormats
                    .createExportFileChooser(Globals.prefs.get(JabRefPreferences.EXPORT_WORKING_DIRECTORY));
            fc.showSaveDialog(frame);
            File file = fc.getSelectedFile();
            if (file == null) {
                return;
            }
            FileFilter ff = fc.getFileFilter();
            if (ff instanceof ExportFileFilter) {

                ExportFileFilter eff = (ExportFileFilter) ff;
                String path = file.getPath();
                if (!path.endsWith(eff.getExtension())) {
                    path = path + eff.getExtension();
                }
                file = new File(path);
                if (file.exists()) {
                    // Warn that the file exists:
                    if (JOptionPane.showConfirmDialog(frame,
                            Localization.lang("'%0' exists. Overwrite file?", file.getName()),
                            Localization.lang("Export"),
                            JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION) {
                        return;
                    }
                }
                final IExportFormat format = eff.getExportFormat();
                List<BibEntry> entries;
                if (selectedOnly) {
                    // Selected entries
                    entries = frame.getCurrentBasePanel().getSelectedEntries();
                } else {
                    // All entries
                    entries = frame.getCurrentBasePanel().getDatabase().getEntries();
                }

                // Set the global variable for this database's file directory before exporting,
                // so formatters can resolve linked files correctly.
                // (This is an ugly hack!)
                Globals.prefs.fileDirForDatabase = frame.getCurrentBasePanel().getBibDatabaseContext()
                        .getFileDirectory();

                // Make sure we remember which filter was used, to set
                // the default for next time:
                Globals.prefs.put(JabRefPreferences.LAST_USED_EXPORT, format.getConsoleName());
                Globals.prefs.put(JabRefPreferences.EXPORT_WORKING_DIRECTORY, file.getParent());

                final File finFile = file;
                final List<BibEntry> finEntries = entries;
                AbstractWorker exportWorker = new AbstractWorker() {

                    String errorMessage;

                    @Override
                    public void run() {
                        try {
                            format.performExport(frame.getCurrentBasePanel().getBibDatabaseContext(),
                                    finFile.getPath(), frame.getCurrentBasePanel().getEncoding(), finEntries);
                        } catch (Exception ex) {
                            LOGGER.warn("Problem exporting", ex);
                            if (ex.getMessage() == null) {
                                errorMessage = ex.toString();
                            } else {
                                errorMessage = ex.getMessage();
                            }
                        }
                    }

                    @Override
                    public void update() {
                        // No error message. Report success:
                        if (errorMessage == null) {
                            frame.output(Localization.lang("%0 export successful", format.getDisplayName()));
                        }
                        // ... or show an error dialog:
                        else {
                            frame.output(Localization.lang("Could not save file.") + " - " + errorMessage);
                            // Need to warn the user that saving failed!
                            JOptionPane.showMessageDialog(frame,
                                    Localization.lang("Could not save file.") + "\n" + errorMessage,
                                    Localization.lang("Save database"), JOptionPane.ERROR_MESSAGE);
                        }
                    }
                };

                // Run the export action in a background thread:
                exportWorker.getWorker().run();
                // Run the update method:
                exportWorker.update();
            }
        }
    }

    return new ExportAction(frame, selectedOnly);
}

From source file:au.org.ala.delta.intkey.ui.MultiStateInputDialog.java

@Override
void handleBtnOKClicked() {
    int[] selectedIndicies = _list.getSelectedIndices();

    // Show confirmation dialog if all of the states have been
    // selected./*from w w w  .j  a  v  a 2s  .  c o  m*/
    if (selectedIndicies.length == _list.getModel().getSize()) {
        int dlgSelection = JOptionPane.showConfirmDialog(this, selectionConfirmationMessage,
                selectionConfirmationTitle, JOptionPane.YES_NO_OPTION);
        if (dlgSelection == JOptionPane.NO_OPTION) {
            return;
        }
    }

    for (int i : selectedIndicies) {
        _inputData.add(i + 1);
    }

    setVisible(false);
}

From source file:jgnash.ui.report.compiled.PayeePieChart.java

private JPanel createPanel() {

    JButton refreshButton = new JButton(rb.getString("Button.Refresh"));

    JButton addFilterButton = new JButton(rb.getString("Button.AddFilter"));
    final JButton saveButton = new JButton(rb.getString("Button.SaveFilters"));
    JButton deleteFilterButton = new JButton(rb.getString("Button.DeleteFilter"));
    JButton clearPrefButton = new JButton(rb.getString("Button.MasterDelete"));

    filterCombo = new JComboBox<>();

    startField = new DatePanel();
    endField = new DatePanel();

    txtAddFilter = new TextField();

    filterList = new ArrayList<>();
    filtersChanged = false;//from   ww  w . ja  va  2 s  . com
    useFilters = new JCheckBox(rb.getString("Label.UseFilters"));
    useFilters.setSelected(true);

    showPercentCheck = new JCheckBox(rb.getString("Button.ShowPercentValues"));

    combo = AccountListComboBox.getFullInstance();

    final LocalDate dStart = DateUtils.getFirstDayOfTheMonth(LocalDate.now().minusYears(1));

    long start = pref.getLong(START_DATE, DateUtils.asEpochMilli(dStart));

    startField.setDate(DateUtils.asLocalDate(start));

    currentAccount = combo.getSelectedAccount();
    PieDataset[] data = createPieDataSet(currentAccount);
    JFreeChart chartCredit = createPieChart(currentAccount, data, 0);
    chartPanelCredit = new ChartPanel(chartCredit, true, true, true, false, true);
    //                         (chart, properties, save, print, zoom, tooltips)
    JFreeChart chartDebit = createPieChart(currentAccount, data, 1);
    chartPanelDebit = new ChartPanel(chartDebit, true, true, true, false, true);

    FormLayout layout = new FormLayout("p, $lcgap, 70dlu, 8dlu, p, $lcgap, 70dlu, $ugap, p, $lcgap:g, left:p",
            "d, $rgap, d, $ugap, f:p:g, $rgap, d");
    DefaultFormBuilder builder = new DefaultFormBuilder(layout);
    layout.setRowGroups(new int[][] { { 1, 3 } });

    // row 1
    builder.append(combo, 9);
    builder.append(useFilters);
    builder.nextLine();
    builder.nextLine();

    // row 3
    builder.append(rb.getString("Label.StartDate"), startField);
    builder.append(rb.getString("Label.EndDate"), endField);
    builder.append(refreshButton);
    builder.append(showPercentCheck);
    builder.nextLine();
    builder.nextLine();

    // row 5
    FormLayout subLayout = new FormLayout("180dlu:g, 1dlu, 180dlu:g", "f:180dlu:g");
    DefaultFormBuilder subBuilder = new DefaultFormBuilder(subLayout);
    subBuilder.append(chartPanelCredit);
    subBuilder.append(chartPanelDebit);

    builder.append(subBuilder.getPanel(), 11);
    builder.nextLine();
    builder.nextLine();

    // row 7
    builder.append(txtAddFilter, 3);
    builder.append(addFilterButton, 3);
    builder.append(saveButton);
    builder.nextLine();

    // row
    builder.append(filterCombo, 3);
    builder.append(deleteFilterButton, 3);
    builder.append(clearPrefButton);
    builder.nextLine();

    JPanel panel = builder.getPanel();

    combo.addActionListener(e -> {
        Account newAccount = combo.getSelectedAccount();

        if (filtersChanged) {
            int result = JOptionPane.showConfirmDialog(null, rb.getString("Message.SaveFilters"), "Warning",
                    JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                saveButton.doClick();
            }
        }
        filtersChanged = false;

        String[] list = POUND_DELIMITER_PATTERN.split(pref.get(FILTER_TAG + newAccount.hashCode(), ""));
        filterList.clear();
        for (String filter : list) {
            if (!filter.isEmpty()) {
                //System.out.println("Adding filter: #" + filter + "#");
                filterList.add(filter);
            }
        }
        refreshFilters();

        setCurrentAccount(newAccount);
        pref.putLong(START_DATE, DateUtils.asEpochMilli(startField.getLocalDate()));
    });

    refreshButton.addActionListener(e -> {
        setCurrentAccount(currentAccount);
        pref.putLong(START_DATE, DateUtils.asEpochMilli(startField.getLocalDate()));
    });

    clearPrefButton.addActionListener(e -> {
        int result = JOptionPane.showConfirmDialog(null, rb.getString("Message.MasterDelete"), "Warning",
                JOptionPane.YES_NO_OPTION);
        if (result == JOptionPane.YES_OPTION) {
            try {
                pref.clear();
            } catch (Exception ex) {
                System.out.println("Exception clearing preferences" + ex);
            }
        }
    });

    saveButton.addActionListener(e -> {
        final StringBuilder sb = new StringBuilder();

        for (String filter : filterList) {
            sb.append(filter);
            sb.append('#');
        }
        //System.out.println("Save = " + FILTER_TAG + currentAccount.hashCode() + " = " + sb.toString());
        pref.put(FILTER_TAG + currentAccount.hashCode(), sb.toString());
        filtersChanged = false;
    });

    addFilterButton.addActionListener(e -> {
        String newFilter = txtAddFilter.getText();
        filterList.remove(newFilter);
        if (!newFilter.isEmpty()) {
            filterList.add(newFilter);
            filtersChanged = true;
            txtAddFilter.setText("");
        }
        refreshFilters();
    });

    deleteFilterButton.addActionListener(e -> {
        if (!filterList.isEmpty()) {
            String filter = (String) filterCombo.getSelectedItem();
            filterList.remove(filter);
            filtersChanged = true;
        }
        refreshFilters();
    });

    useFilters.addActionListener(e -> setCurrentAccount(currentAccount));

    showPercentCheck.addActionListener(e -> {
        ((PiePlot) chartPanelCredit.getChart().getPlot())
                .setLabelGenerator(showPercentCheck.isSelected() ? percentLabels : defaultLabels);
        ((PiePlot) chartPanelDebit.getChart().getPlot())
                .setLabelGenerator(showPercentCheck.isSelected() ? percentLabels : defaultLabels);
    });

    return panel;
}

From source file:edu.cmu.cs.diamond.pathfind.DjangoAnnotationStore.java

private void login(String loginuri) throws IOException {
    String username = prefs.get("username", "");
    String password = "";

    JLabel label = new JLabel("Please enter your username and password:");
    JTextField jtf = new JTextField(username);
    JPasswordField jpf = new JPasswordField();
    int dialogResult = JOptionPane.showConfirmDialog(null, new Object[] { label, jtf, jpf },
            "Login to PathFind", JOptionPane.OK_CANCEL_OPTION);
    if (dialogResult == JOptionPane.OK_OPTION) {
        username = jtf.getText();//from  w ww  . ja va2 s  .  c om
        prefs.put("username", username);
        password = new String(jpf.getPassword());
    } else {
        throw new IOException("User refused to login");
    }

    // get the form to get the cookies
    GetMethod form = new GetMethod(loginuri);
    try {
        if (httpClient.executeMethod(form) != 200) {
            throw new IOException("Can't GET " + loginuri);
        }
    } finally {
        form.releaseConnection();
    }

    // get cookies
    Cookie[] cookies = httpClient.getState().getCookies();
    for (Cookie c : cookies) {
        System.out.println(c);
        if (c.getName().equals("csrftoken")) {
            csrftoken = c.getValue();
            break;
        }
    }

    // now, post
    PostMethod post = new PostMethod(loginuri);
    try {
        post.addRequestHeader("Referer", loginuri);
        NameValuePair params[] = { new NameValuePair("username", username),
                new NameValuePair("password", password), new NameValuePair("csrfmiddlewaretoken", csrftoken) };
        //System.out.println(Arrays.toString(params));
        post.setRequestBody(params);
        httpClient.executeMethod(post);
        System.out.println(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}

From source file:es.emergya.ui.plugins.admin.AdminRoles.java

protected SummaryAction getSummaryAction(final Rol r) {
    SummaryAction action = new SummaryAction(r) {

        private static final long serialVersionUID = -601099799668196685L;

        @Override/*from   w  ww.j  a  va 2s  .co  m*/
        protected JFrame getSummaryDialog() {
            final String titulo;
            final String cabecera;
            if (isNew) {
                titulo = i18n.getString("admin.roles.tituloVentana.nuevo"); //$NON-NLS-1$
                cabecera = i18n.getString("admin.roles.cabecera.nuevo");//$NON-NLS-1$
            } else {
                titulo = i18n.getString("admin.roles.tituloVentana.existente"); //$NON-NLS-1$
                cabecera = i18n.getString("admin.roles.cabecera.existente");//$NON-NLS-1$
            }
            final String label_cabecera = i18n.getString("admin.roles7"); //$NON-NLS-1$
            final String label_pie = i18n.getString("admin.roles8"); //$NON-NLS-1$
            final String centered_label = i18n.getString("admin.roles9"); //$NON-NLS-1$
            final String left_label = i18n.getString("admin.roles10"); //$NON-NLS-1$
            final String right_label = i18n.getString("admin.roles11"); //$NON-NLS-1$

            final Flota[] left_items = RolConsultas.getDisponibles(r);
            final Flota[] right_items = RolConsultas.getAsigned(r);
            final AdminPanel.SaveOrUpdateAction<Rol> guardar = roles.new SaveOrUpdateAction<Rol>(r) {

                private static final long serialVersionUID = 7447770196943361404L;

                @Override
                public void actionPerformed(ActionEvent e) {
                    if (textfieldCabecera.getText().trim().isEmpty()) {
                        JOptionPane.showMessageDialog(super.frame, i18n.getString("admin.roles13")); //$NON-NLS-1$
                    } else if (isNew && RolConsultas.alreadyExists(textfieldCabecera.getText().trim())) {
                        JOptionPane.showMessageDialog(super.frame, i18n.getString("admin.roles14")); //$NON-NLS-1$
                    } else if (textfieldCabecera.getText().isEmpty()) {
                        JOptionPane.showMessageDialog(super.frame, i18n.getString("admin.roles15")); //$NON-NLS-1$
                    } else if (cambios) {
                        int i = JOptionPane.showConfirmDialog(super.frame, i18n.getString("admin.roles16"), //$NON-NLS-1$
                                i18n.getString("admin.roles17"), //$NON-NLS-1$
                                JOptionPane.YES_NO_CANCEL_OPTION);

                        if (i == JOptionPane.YES_OPTION) {

                            if (original == null) {
                                original = new Rol();
                            }

                            original.setInfoAdicional(textfieldPie.getText());
                            original.setNombre(textfieldCabecera.getText());

                            HashSet<Flota> flotas = new HashSet<Flota>();
                            for (Object r : ((DefaultListModel) right.getModel()).toArray()) {
                                if (r instanceof Flota) {
                                    flotas.add((Flota) r);
                                } else {
                                    log.error(i18n.getString("admin.roles18")); //$NON-NLS-1$
                                }
                            }
                            original.setFlotas(flotas);

                            RolAdmin.saveOrUpdate(original);
                            PluginEventHandler.fireChange(AdminRoles.this);

                            cambios = false;
                            original = null;

                            roles.setTableData(getAll(new Rol()));

                            closeFrame();
                        } else if (i == JOptionPane.NO_OPTION) {
                            closeFrame();
                        }
                    } else {
                        closeFrame();
                    }
                }
            };

            d = generateIconDialog(label_cabecera, label_pie, centered_label, titulo, left_items, right_items,
                    left_label, right_label, guardar, LogicConstants.getIcon(i18n.getString("admin.roles19")),
                    cabecera, null); //$NON-NLS-1$ //$NON-NLS-2$

            if (r != null) {
                textfieldCabecera.setText(r.getNombre());
                // textfieldCabecera.setEnabled(false);
                textfieldCabecera.setEditable(false);
                textfieldPie.setText(r.getInfoAdicional());
            } else {
                textfieldCabecera.setText(""); //$NON-NLS-1$
                textfieldCabecera.setEnabled(true);
                textfieldPie.setText(""); //$NON-NLS-1$
            }
            cambios = false;

            return d;
        }
    };

    return action;
}

From source file:es.emergya.ui.plugins.admin.AdminSquads.java

protected SummaryAction getSummaryAction(final Patrulla p) {
    SummaryAction action = new SummaryAction(p) {

        private static final long serialVersionUID = -8344125339845145826L;

        @Override/*from   w w  w  . j  a va 2  s  . c  o  m*/
        protected JFrame getSummaryDialog() {
            final String label_cabecera = "Nombre Patrulla:";
            final String label_pie = "Info Adicional:";
            final String centered_label = "Recursos:";
            final String left_label = "Recursos disponibles";
            final String right_label = "Recursos asignados";
            final String titulo, cabecera;
            if (isNew) {
                titulo = i18n.getString("Squads.barraTitulo.nuevo");
                cabecera = i18n.getString("Squads.cabecera.nuevo");

            } else {
                titulo = i18n.getString("Squads.barraTitulo.existente");
                cabecera = i18n.getString("Squads.cabecera.existente");
            }
            final Recurso[] left_items = RecursoConsultas.getNotAsigned(p);
            for (Recurso r : left_items)
                r.setTipoToString(Recurso.TIPO_TOSTRING.PATRULLA);
            final Recurso[] right_items = RecursoConsultas.getAsigned(p);
            for (Recurso r : right_items)
                r.setTipoToString(Recurso.TIPO_TOSTRING.PATRULLA);
            final AdminPanel.SaveOrUpdateAction<Patrulla> guardar = squads.new SaveOrUpdateAction<Patrulla>(p) {

                private static final long serialVersionUID = 7447770296943341404L;

                @Override
                public void actionPerformed(ActionEvent e) {

                    if (isNew && PatrullaConsultas.alreadyExists(textfieldCabecera.getText())) {
                        JOptionPane.showMessageDialog(super.frame, "Ya existe una patrulla con ese nombre.");
                    } else if (textfieldCabecera.getText().isEmpty()) {
                        JOptionPane.showMessageDialog(super.frame, "El nombre es obligatorio.");
                    } else if (cambios) {
                        int i = JOptionPane.showConfirmDialog(super.frame, "Desea guardar los cambios?",
                                "Guardar", JOptionPane.YES_NO_CANCEL_OPTION);

                        if (i == JOptionPane.YES_OPTION) {

                            if (original == null) {
                                original = new Patrulla();
                            }

                            original.setInfoAdicional(textfieldPie.getText());
                            original.setNombre(textfieldCabecera.getText());

                            HashSet<Recurso> recursos = new HashSet<Recurso>();
                            for (Object r : ((DefaultListModel) right.getModel()).toArray()) {
                                if (r instanceof Recurso) {
                                    recursos.add((Recurso) r);
                                    ((Recurso) r).setPatrullas(original);
                                } else {
                                    log.error("El objeto no era un recurso");
                                }
                            }
                            original.setRecursos(recursos);

                            PatrullaAdmin.saveOrUpdate(original);
                            PluginEventHandler.fireChange(AdminSquads.this);

                            cambios = false;
                            original = null;

                            squads.setTableData(getAll(new Patrulla()));

                            closeFrame();
                        } else if (i == JOptionPane.NO_OPTION) {
                            closeFrame();
                        }
                    } else {
                        closeFrame();
                    }
                }
            };

            // if (d == null)
            d = generateIconDialog(label_cabecera, label_pie, centered_label, titulo, left_items, right_items,
                    left_label, right_label, guardar, LogicConstants.getIcon("tittleficha_icon_patrulla"),
                    cabecera, null);

            if (p != null) {
                textfieldCabecera.setText(p.getNombre());
                textfieldPie.setText(p.getInfoAdicional());
                textfieldCabecera.setEditable(false);
            } else {
                textfieldCabecera.setText("");
                textfieldPie.setText("");
            }
            cambios = false;

            return d;
        }
    };

    return action;
}