Example usage for javax.swing JOptionPane YES_OPTION

List of usage examples for javax.swing JOptionPane YES_OPTION

Introduction

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

Prototype

int YES_OPTION

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

Click Source Link

Document

Return value from class method if YES is chosen.

Usage

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

/**
 * Asks the user a binary yes or no question.
 *
 * @param parentComponent the component/*  ww  w  . j a v  a2s  . co  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: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 w  w w. j a  va2s.c o  m
    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:gdt.jgui.entity.fields.JFieldsEditor.java

/**
 * Get the context menu.//  w  w w  .ja v a2 s  .c  o m
 * @return the context menu.
 */
@Override
public JMenu getContextMenu() {
    menu = new JMenu("Context");
    menu.addMenuListener(new MenuListener() {
        @Override
        public void menuSelected(MenuEvent e) {
            //         System.out.println("FieldsEditor:getConextMenu:menu selected");

            if (editCellItem != null)
                menu.remove(editCellItem);
            if (deleteItemsItem != null)
                menu.remove(deleteItemsItem);
            if (copyItem != null)
                menu.remove(copyItem);
            if (pasteItem != null)
                menu.remove(pasteItem);
            if (cutItem != null)
                menu.remove(cutItem);

            if (hasEditingCell()) {
                editCellItem = new JMenuItem("Edit item");
                editCellItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        try {
                            JTextEditor textEditor = new JTextEditor();
                            String locator$ = textEditor.getLocator();
                            locator$ = Locator.append(locator$, Entigrator.ENTIHOME, entihome$);
                            locator$ = Locator.append(locator$, EntityHandler.ENTITY_KEY, entityKey$);
                            String responseLocator$ = getEditCellLocator();
                            text$ = Locator.getProperty(responseLocator$, JTextEditor.TEXT);
                            locator$ = Locator.append(locator$, JTextEditor.TEXT, text$);
                            //                  System.out.println("FieldsEditor:edit cell:text="+text$);
                            locator$ = Locator.append(locator$, JRequester.REQUESTER_RESPONSE_LOCATOR,
                                    Locator.compressText(responseLocator$));
                            JConsoleHandler.execute(console, locator$);
                        } catch (Exception ee) {
                            LOGGER.severe(ee.toString());
                        }
                    }
                });
                menu.add(editCellItem);
            }
            if (hasSelectedRows()) {
                deleteItemsItem = new JMenuItem("Delete items");
                deleteItemsItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        int response = JOptionPane.showConfirmDialog(JFieldsEditor.this,
                                "Delete selected fields ?", "Confirm", JOptionPane.YES_NO_OPTION,
                                JOptionPane.QUESTION_MESSAGE);
                        if (response == JOptionPane.YES_OPTION) {
                            deleteRows();
                        }
                    }
                });
                menu.add(deleteItemsItem);
                copyItem = new JMenuItem("Copy");
                copyItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        copy(false);
                    }
                });
                menu.add(copyItem);
                cutItem = new JMenuItem("Cut");
                cutItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        copy(true);
                    }
                });
                menu.add(cutItem);
            }
            if (hasFieldsToPaste()) {
                pasteItem = new JMenuItem("Paste");
                pasteItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        try {
                            String[] sa = console.clipboard.getContent();
                            Properties locator;
                            String type$;
                            String sourceEntityKey$;
                            Sack sourceEntity;
                            String sourceEntihome$;
                            Entigrator sourceEntigrator;
                            for (String aSa : sa) {
                                //System.out.println("FieldsEditor:paste:"+aSa);
                                locator = Locator.toProperties(aSa);
                                type$ = locator.getProperty(Locator.LOCATOR_TYPE);
                                if (LOCATOR_TYPE_FIELD.equals(type$)) {
                                    String action$ = locator.getProperty(JRequester.REQUESTER_ACTION);
                                    String name$ = locator.getProperty(CELL_FIELD_NAME);
                                    String value$ = locator.getProperty(CELL_FIELD_VALUE);
                                    if (name$ != null) {
                                        if (ACTION_COPY_FIELDS.equals(action$))
                                            entity.putElementItem("field", new Core(null, name$, value$));
                                        if (ACTION_CUT_FIELDS.equals(action$)) {
                                            entity.putElementItem("field", new Core(null, name$, value$));
                                            sourceEntihome$ = locator.getProperty(Entigrator.ENTIHOME);
                                            sourceEntigrator = console.getEntigrator(sourceEntihome$);
                                            sourceEntityKey$ = locator.getProperty(EntityHandler.ENTITY_KEY);
                                            sourceEntity = sourceEntigrator.getEntityAtKey(sourceEntityKey$);
                                            sourceEntity.removeElementItem("field", name$);
                                            sourceEntigrator.save(sourceEntity);
                                        }
                                    }
                                }
                            }
                            entigrator.save(entity);
                            Core[] ca = entity.elementGet("field");
                            replaceTable(ca);
                        } catch (Exception ee) {
                            LOGGER.info(ee.toString());
                        }
                    }
                });
                menu.add(pasteItem);
            }
        }

        @Override
        public void menuDeselected(MenuEvent e) {
        }

        @Override
        public void menuCanceled(MenuEvent e) {
        }
    });
    doneItem = new JMenuItem("Done");
    doneItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            save();
            if (requesterResponseLocator$ != null) {
                try {
                    byte[] ba = Base64.decodeBase64(requesterResponseLocator$);
                    String responseLocator$ = new String(ba, "UTF-8");
                    responseLocator$ = Locator.append(responseLocator$, Entigrator.ENTIHOME, entihome$);
                    responseLocator$ = Locator.append(responseLocator$, EntityHandler.ENTITY_KEY, entityKey$);
                    //  System.out.println("FieldsEditor:done.response locator="+responseLocator$);
                    JConsoleHandler.execute(console, responseLocator$);
                } catch (Exception ee) {
                    LOGGER.severe(ee.toString());
                }
            } else
                console.back();
        }
    });
    menu.add(doneItem);
    JMenuItem cancelItem = new JMenuItem("Cancel");
    cancelItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            console.back();
        }
    });
    menu.add(cancelItem);
    menu.addSeparator();
    JMenuItem addItemItem = new JMenuItem("Add item");
    addItemItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            addRow();
        }
    });
    menu.add(addItemItem);
    if (postMenu != null) {
        //System.out.println("JFieldsEditor:postMenu="+postMenu.length);
        for (JMenuItem jmi : postMenu)
            menu.add(jmi);
    }
    //else
    //   System.out.println("JFieldsEditor:postMenu empty");

    return menu;
}

From source file:pt.lsts.neptus.console.bathymLayer.TidePanel.java

@Override
public void initSubPanel() {
    storedMenuPath = I18n.text("Tools") + ">" + I18n.text("Tides") + ">"
            + I18n.textf("Using '%file'", GeneralPreferences.tidesFile.getName());
    tidesItem = addMenuItem(storedMenuPath, null, new ActionListener() {
        @Override//w  w w .  j  a  va2s.co m
        public void actionPerformed(ActionEvent e) {
            JMenuItem menu = (JMenuItem) e.getSource();
            Thread t = new Thread("Tide chooser") {
                @Override
                public void run() {
                    try {
                        File usedTidesSource = GeneralPreferences.tidesFile;
                        String currentSource = usedTidesSource == null || !usedTidesSource.exists() ? null
                                : usedTidesSource.getName();
                        Date startDate = new Date(System.currentTimeMillis() - 2 * DateTimeUtil.DAY);
                        Date endDate = new Date(System.currentTimeMillis() + 3 * DateTimeUtil.DAY);
                        String harbor = TidePredictionFactory.showTidesSourceChooserGuiPopup(getConsole(),
                                currentSource, startDate, endDate);
                        if (harbor != null && !harbor.isEmpty()
                                && TidePredictionFactory.getTidesSourceFileFrom(harbor).exists()) {
                            GeneralPreferences.tidesFile = TidePredictionFactory.getTidesSourceFileFrom(harbor);
                            GeneralPreferences.saveProperties();
                            preferencesUpdated();
                            // Force the tide file reload
                            TidePredictionFactory.getTideLevel(System.currentTimeMillis());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        menu.setEnabled(true);
                    }
                }
            };
            t.setDaemon(true);
            menu.setEnabled(false);
            t.run();
        }
    });
    //        tidesItem.setEnabled(false);

    addMenuItem(I18n.text("Tools") + ">" + I18n.text("Tides") + ">" + I18n.text("Update Predictions"), null,
            new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JMenuItem menu = (JMenuItem) e.getSource();
                    Thread t = new Thread("Tide fetcher") {
                        public void run() {
                            try {
                                String harbor = TidePredictionFactory.fetchData(getConsole());
                                if (harbor != null && !harbor.isEmpty()) {
                                    File used = GeneralPreferences.tidesFile;
                                    File f = new File(ConfigFetch.getConfFolder() + "/tides/" + harbor + "."
                                            + TidePredictionFactory.defaultTideFormat);
                                    if (f.exists() && !f.getAbsolutePath().equals(used.getAbsolutePath())) {
                                        int resp = GuiUtils.confirmDialog(getConsole(),
                                                I18n.text("Tide Predictions"),
                                                I18n.textf(
                                                        "The selected location does not match the current location in use (%harbor). Do you wish to set the current location as %selection?",
                                                        used.getName(),
                                                        harbor + "." + TidePredictionFactory.defaultTideFormat),
                                                ModalityType.DOCUMENT_MODAL);

                                        if (resp == JOptionPane.YES_OPTION) {
                                            GeneralPreferences.tidesFile = f;
                                            GeneralPreferences.saveProperties();
                                            preferencesUpdated();
                                            // Force the tide file reload
                                            TidePredictionFactory.getTideLevel(System.currentTimeMillis());
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            } finally {
                                menu.setEnabled(true);
                            }
                        };
                    };
                    t.setDaemon(true);
                    menu.setEnabled(false);
                    t.start();
                }
            });

    ts = new TimeSeries(I18n.text("Tide level"));
    tsc.addSeries(ts);

    for (double i = -12; i < 12; i += 0.25) {
        Date d = new Date(System.currentTimeMillis() + (long) (i * 1000 * 3600));
        ts.addOrUpdate(new Millisecond(d), TidePredictionFactory.getTideLevel(d));
    }
    timeSeriesChart.getXYPlot().addDomainMarker(marker);
    levelMarker.setValue(TidePredictionFactory.getTideLevel(new Date()));
    timeSeriesChart.getXYPlot().addRangeMarker(levelMarker);
}

From source file:net.sf.jabref.gui.desktop.JabRefDesktop.java

public static boolean openExternalFileUnknown(JabRefFrame frame, BibEntry entry,
        BibDatabaseContext databaseContext, String link, UnknownExternalFileType fileType) throws IOException {

    String cancelMessage = Localization.lang("Unable to open file.");
    String[] options = new String[] { Localization.lang("Define '%0'", fileType.getName()),
            Localization.lang("Change file type"), Localization.lang("Cancel") };
    String defOption = options[0];
    int answer = JOptionPane.showOptionDialog(frame,
            Localization.lang(//from w  ww .  j a  v  a  2  s .  c o m
                    "This external link is of the type '%0', which is undefined. What do you want to do?",
                    fileType.getName()),
            Localization.lang("Undefined file type"), JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, options, defOption);
    if (answer == JOptionPane.CANCEL_OPTION) {
        frame.output(cancelMessage);
        return false;
    } else if (answer == JOptionPane.YES_OPTION) {
        // User wants to define the new file type. Show the dialog:
        ExternalFileType newType = new ExternalFileType(fileType.getName(), "", "", "", "new",
                IconTheme.JabRefIcon.FILE.getSmallIcon());
        ExternalFileTypeEntryEditor editor = new ExternalFileTypeEntryEditor(frame, newType);
        editor.setVisible(true);
        if (editor.okPressed()) {
            // Get the old list of types, add this one, and update the list in prefs:
            List<ExternalFileType> fileTypes = new ArrayList<>(
                    ExternalFileTypes.getInstance().getExternalFileTypeSelection());
            fileTypes.add(newType);
            Collections.sort(fileTypes);
            ExternalFileTypes.getInstance().setExternalFileTypes(fileTypes);
            // Finally, open the file:
            return openExternalFileAnyFormat(databaseContext, link, Optional.of(newType));
        } else {
            // Canceled:
            frame.output(cancelMessage);
            return false;
        }
    } else {
        // User wants to change the type of this link.
        // First get a model of all file links for this entry:
        FileListTableModel tModel = new FileListTableModel();
        Optional<String> oldValue = entry.getFieldOptional(FieldName.FILE);
        oldValue.ifPresent(tModel::setContent);
        FileListEntry flEntry = null;
        // Then find which one we are looking at:
        for (int i = 0; i < tModel.getRowCount(); i++) {
            FileListEntry iEntry = tModel.getEntry(i);
            if (iEntry.link.equals(link)) {
                flEntry = iEntry;
                break;
            }
        }
        if (flEntry == null) {
            // This shouldn't happen, so I'm not sure what to put in here:
            throw new RuntimeException("Could not find the file list entry " + link + " in " + entry);
        }

        FileListEntryEditor editor = new FileListEntryEditor(frame, flEntry, false, true, databaseContext);
        editor.setVisible(true, false);
        if (editor.okPressed()) {
            // Store the changes and add an undo edit:
            String newValue = tModel.getStringRepresentation();
            UndoableFieldChange ce = new UndoableFieldChange(entry, FieldName.FILE, oldValue.orElse(null),
                    newValue);
            entry.setField(FieldName.FILE, newValue);
            frame.getCurrentBasePanel().getUndoManager().addEdit(ce);
            frame.getCurrentBasePanel().markBaseChanged();
            // Finally, open the link:
            return openExternalFileAnyFormat(databaseContext, flEntry.link, flEntry.type);
        } else {
            // Canceled:
            frame.output(cancelMessage);
            return false;
        }
    }
}

From source file:com.bsoft.baseframe.baseframe_utils.beanUtils.Classgenerator.java

/**
 * ?//from  w w w.  ja va2 s. co  m
 * @param msg_code int
 */
private void showMsg(int msg_code) {
    String message = "";
    boolean flag = false;
    switch (msg_code) {
    case 0:
        flag = true;
        message = "???";
        break;
    case 1:
        message = "?????";
        break;
    case 2:
        message = "??";
        break;
    case 3:
        message = "XML??";
        break;
    case 4:
        message = "????";
        break;
    case 5:
        message = "???";
        break;
    }
    JOptionPane.showMessageDialog(this, message, "", JOptionPane.WARNING_MESSAGE);
    if (flag) {
        int closable = JOptionPane.showConfirmDialog(null,
                "???\n??", "??", JOptionPane.YES_NO_OPTION,
                JOptionPane.INFORMATION_MESSAGE);
        if (JOptionPane.YES_OPTION == closable) {
            System.exit(0);
        }
        return;
    }
}

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/*ww  w. j av a2s. co 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;
}

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//  w ww .  j  ava2 s  .  c o 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:com.floreantpos.bo.ui.explorer.QuickMaintenanceExplorer.java

private static void quickMaintainMenuCategory(MenuCategory menuCategory) {
    try {/*from  w w w . jav  a 2s  . c  o  m*/
        if (menuCategory.getId() != null) {
            if (btnCopy.isSelected()) {
                MenuCategory newMenuCategory = new MenuCategory();
                PropertyUtils.copyProperties(newMenuCategory, menuCategory);
                newMenuCategory.setId(null);
                menuCategory = newMenuCategory;
            } else if (btnDelete.isSelected()) {
                if (POSMessageDialog.showYesNoQuestionDialog(POSUtil.getFocusedWindow(),
                        POSConstants.CONFIRM_DELETE, POSConstants.DELETE) != JOptionPane.YES_OPTION) {
                    return;
                }

                MenuGroupDAO menuGroupDao = new MenuGroupDAO();
                List<MenuGroup> menuGroups = menuGroupDao.findByParent(menuCategory);

                if (menuGroups.size() > 0) {
                    if (POSMessageDialog.showYesNoQuestionDialog(POSUtil.getFocusedWindow(),
                            Messages.getString("MenuCategoryExplorer.0"), //$NON-NLS-1$
                            POSConstants.DELETE) != JOptionPane.YES_OPTION) {
                        return;
                    }
                    menuGroupDao.releaseParent(menuGroups);
                }
                MenuCategoryDAO dao = new MenuCategoryDAO();
                dao.delete(menuCategory);
                OrderView.getInstance().getCategoryView().updateView(menuCategory);
                return;
            }
        }
        MenuCategoryForm editor = new MenuCategoryForm(menuCategory);
        BeanEditorDialog dialog = new BeanEditorDialog(Application.getPosWindow(), editor);
        dialog.open();
        if (dialog.isCanceled())
            return;
        OrderView.getInstance().getCategoryView().updateView(menuCategory);
        return;
    } catch (Exception e) {
        return;
    }
}

From source file:eu.ggnet.dwoss.receipt.UiUnitSupport.java

private UniqueUnit optionalChangeStock(UniqueUnit uniqueUnit, StockUnit stockUnit, Stock localStock,
        Window parent, String account) {
    if (!stockUnit.isInStock())
        return uniqueUnit;
    if (localStock.equals(stockUnit.getStock()))
        return uniqueUnit;
    if (stockUnit.isInTransaction()) {
        JOptionPane.showMessageDialog(parent,
                "Achtung, Gert ist nicht auf " + localStock.getName() + ",\n"
                        + "aber Gert ist auch auf einer Transaktion.\n"
                        + "Automatische Lagernderung nicht mglich !");
        return uniqueUnit;
    }//from   w w w  .j av a2s . c  o  m
    int option = JOptionPane.showConfirmDialog(parent,
            "Gert steht nicht auf " + localStock.getName()
                    + ", welches als Standort angegeben ist. Gertestandort ndern ?",
            "Standortabweichung", JOptionPane.YES_NO_OPTION);
    if (option == JOptionPane.YES_OPTION) {
        ComboBoxDialog<Stock> dialog = new ComboBoxDialog<>(parent,
                lookup(StockAgent.class).findAll(Stock.class).toArray(new Stock[0]), new StockCellRenderer());
        dialog.setSelection(localStock);
        dialog.setVisible(true);
        if (dialog.isOk())
            return unitProcessor.transfer(uniqueUnit, dialog.getSelection().getId(), account);
    }
    return uniqueUnit;
}