Example usage for javax.swing JOptionPane YES_NO_OPTION

List of usage examples for javax.swing JOptionPane YES_NO_OPTION

Introduction

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

Prototype

int YES_NO_OPTION

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

Click Source Link

Document

Type used for showConfirmDialog.

Usage

From source file:com.vgi.mafscaling.VECalc.java

protected void loadLogFile() {
    fileChooser.setMultiSelectionEnabled(true);
    if (JFileChooser.APPROVE_OPTION != fileChooser.showOpenDialog(this))
        return;/*from   ww  w.  j a  v a2s  .c om*/
    File[] files = fileChooser.getSelectedFiles();
    for (File file : files) {
        BufferedReader br = null;
        ArrayDeque<String[]> buffer = new ArrayDeque<String[]>();
        try {
            br = new BufferedReader(new FileReader(file.getAbsoluteFile()));
            String line = br.readLine();
            if (line != null) {
                String[] elements = line.split("(\\s*)?,(\\s*)?", -1);
                getColumnsFilters(elements);

                boolean resetColumns = false;
                if (logThrottleAngleColIdx >= 0 || logFfbColIdx >= 0 || logSdColIdx >= 0
                        || (logWbAfrColIdx >= 0 && isOl) || (logStockAfrColIdx >= 0 && !isOl)
                        || (logAfLearningColIdx >= 0 && !isOl) || (logAfCorrectionColIdx >= 0 && !isOl)
                        || logRpmColIdx >= 0 || logMafColIdx >= 0 || logIatColIdx >= 0 || logMpColIdx >= 0) {
                    if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(null,
                            "Would you like to reset column names or filter values?", "Columns/Filters Reset",
                            JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE))
                        resetColumns = true;
                }

                if (resetColumns || logThrottleAngleColIdx < 0 || logFfbColIdx < 0 || logSdColIdx < 0
                        || (logWbAfrColIdx < 0 && isOl) || (logStockAfrColIdx < 0 && !isOl)
                        || (logAfLearningColIdx < 0 && !isOl) || (logAfCorrectionColIdx < 0 && !isOl)
                        || logRpmColIdx < 0 || logMafColIdx < 0 || logIatColIdx < 0 || logMpColIdx < 0) {
                    ColumnsFiltersSelection selectionWindow = new VEColumnsFiltersSelection(false);
                    if (!selectionWindow.getUserSettings(elements) || !getColumnsFilters(elements))
                        return;
                }

                if (logClOlStatusColIdx == -1)
                    clValue = -1;

                String[] flds;
                String[] afrflds;
                boolean removed = false;
                int i = 2;
                int clol = -1;
                int row = getLogTableEmptyRow();
                double thrtlMaxChange2 = thrtlMaxChange + thrtlMaxChange / 2.0;
                double throttle = 0;
                double pThrottle = 0;
                double ppThrottle = 0;
                double afr = 0;
                double rpm;
                double ffb;
                double iat;
                clearRunTables();
                setCursor(new Cursor(Cursor.WAIT_CURSOR));
                for (int k = 0; k <= afrRowOffset && line != null; ++k) {
                    line = br.readLine();
                    if (line != null)
                        buffer.addFirst(line.split(",", -1));
                }
                try {
                    while (line != null && buffer.size() > afrRowOffset) {
                        afrflds = buffer.getFirst();
                        flds = buffer.removeLast();
                        line = br.readLine();
                        if (line != null)
                            buffer.addFirst(line.split(",", -1));
                        ppThrottle = pThrottle;
                        pThrottle = throttle;
                        throttle = Double.valueOf(flds[logThrottleAngleColIdx]);
                        try {
                            if (row > 0 && Math.abs(pThrottle - throttle) > thrtlMaxChange) {
                                if (!removed)
                                    Utils.removeRow(row--, logDataTable);
                                removed = true;
                            } else if (row <= 0 || Math.abs(ppThrottle - throttle) <= thrtlMaxChange2) {
                                // Filters
                                afr = (isOl ? Double.valueOf(afrflds[logWbAfrColIdx])
                                        : Double.valueOf(afrflds[logStockAfrColIdx]));
                                rpm = Double.valueOf(flds[logRpmColIdx]);
                                ffb = Double.valueOf(flds[logFfbColIdx]);
                                iat = Double.valueOf(flds[logIatColIdx]);
                                if (clValue != -1)
                                    clol = Integer.valueOf(flds[logClOlStatusColIdx]);
                                boolean flag = isOl ? ((afr <= afrMax || throttle >= thrtlMin) && afr <= afrMax)
                                        : (afrMin <= afr);
                                if (flag && clol == clValue && rpmMin <= rpm && ffbMin <= ffb && ffb <= ffbMax
                                        && iat <= iatMax) {
                                    removed = false;
                                    if (!isOl)
                                        trims.add(Double.valueOf(flds[logAfLearningColIdx])
                                                + Double.valueOf(flds[logAfCorrectionColIdx]));
                                    Utils.ensureRowCount(row + 1, logDataTable);
                                    logDataTable.setValueAt(rpm, row, 0);
                                    logDataTable.setValueAt(iat, row, 1);
                                    logDataTable.setValueAt(Double.valueOf(flds[logMpColIdx]), row, 2);
                                    logDataTable.setValueAt(ffb, row, 3);
                                    logDataTable.setValueAt(afr, row, 4);
                                    logDataTable.setValueAt(Double.valueOf(flds[logMafColIdx]), row, 5);
                                    logDataTable.setValueAt(Double.valueOf(flds[logSdColIdx]), row, 6);
                                    row += 1;
                                } else
                                    removed = true;
                            } else
                                removed = true;
                        } catch (NumberFormatException e) {
                            logger.error(e);
                            JOptionPane.showMessageDialog(null,
                                    "Error parsing number at " + file.getName() + " line " + i + ": " + e,
                                    "Error processing file", JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                        i += 1;
                    }
                } finally {
                    setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                }
            }
        } catch (Exception e) {
            logger.error(e);
            JOptionPane.showMessageDialog(null, e, "Error opening file", JOptionPane.ERROR_MESSAGE);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
        }
    }
}

From source file:com.diversityarrays.kdxplore.trials.TrialViewPanel.java

private void doRemoveTraitInstancesWithoutSamples() {
    TableModel model = trialDataTable.getModel();
    if (model instanceof TrialData) {
        TrialData trialData = (TrialData) model;
        TraitNameStyle tns = trialData.trial.getTraitNameStyle();

        List<Integer> modelRows = GuiUtil.getSelectedModelRows(trialDataTable);
        List<TraitInstance> withData = new ArrayList<>();
        List<TraitInstance> withoutData = new ArrayList<>();

        for (Integer row : modelRows) {
            TraitInstance ti = trialData.getTraitInstanceAt(row);
            int traitId = ti.getTraitId();
            int instanceNumber = ti.getInstanceNumber();

            boolean[] anyScored = new boolean[1];
            BiPredicate<SampleGroup, KdxSample> sampleVisitor = new BiPredicate<SampleGroup, KdxSample>() {
                @Override//from   w  w w  .  ja  v  a  2s.  com
                public boolean test(SampleGroup sg, KdxSample s) {
                    if (traitId != s.getTraitId()) {
                        return true; // not the correct trait
                    }
                    if (instanceNumber != s.getTraitInstanceNumber()) {
                        return true; // not the correct trait
                    }
                    // Ok - it is for this traitInstance
                    if (s.hasBeenScored()) {
                        anyScored[0] = true;
                        return false;
                    }
                    return true; // keep looking for scored samples
                }
            };
            trialData.visitSampleGroupSamples(sampleVisitor);
            if (anyScored[0]) {
                withData.add(ti);
            } else {
                withoutData.add(ti);
            }
        }

        if (withoutData.isEmpty()) {
            if (withData.isEmpty()) {
                MsgBox.warn(TrialViewPanel.this, "Nothing to do!", "Remove Trait/Instances");
            } else {
                String s = withData.stream().map(ti -> tns.makeTraitInstanceName(ti))
                        .collect(Collectors.joining("</li><li>", "<html>With Data:<ul><li>", "</li></ul>"));
                MsgBox.warn(TrialViewPanel.this, s, "Cannot remove Traits with Data");
            }
        } else {
            String s = withoutData.stream().map(ti -> tns.makeTraitInstanceName(ti))
                    .collect(Collectors.joining("</li><li>", "<html><ul><li>", "</li></ul>"));
            int answer = JOptionPane.showConfirmDialog(TrialViewPanel.this, s,
                    "Confirm Trait Instance Removeal", JOptionPane.YES_NO_OPTION);
            if (JOptionPane.YES_OPTION == answer) {
                try {
                    offlineData.getKdxploreDatabase().removeTraitInstancesFromTrial(trial, withoutData);
                } catch (IOException e) {
                    MsgBox.warn(TrialViewPanel.this, e, "Remove Trait/Instances from Trial");
                } finally {
                    setCurrentTrialDetails(trial, false);
                    onTraitInstancesRemoved.accept(trial);
                }
            }
        }
    }
}

From source file:DialogDemo.java

/** Creates the panel shown by the second tab. */
private JPanel createFeatureDialogBox() {
    final int numButtons = 5;
    JRadioButton[] radioButtons = new JRadioButton[numButtons];
    final ButtonGroup group = new ButtonGroup();

    JButton showItButton = null;//from w  ww  .ja va  2s.c om

    final String pickOneCommand = "pickone";
    final String textEnteredCommand = "textfield";
    final String nonAutoCommand = "nonautooption";
    final String customOptionCommand = "customoption";
    final String nonModalCommand = "nonmodal";

    radioButtons[0] = new JRadioButton("Pick one of several choices");
    radioButtons[0].setActionCommand(pickOneCommand);

    radioButtons[1] = new JRadioButton("Enter some text");
    radioButtons[1].setActionCommand(textEnteredCommand);

    radioButtons[2] = new JRadioButton("Non-auto-closing dialog");
    radioButtons[2].setActionCommand(nonAutoCommand);

    radioButtons[3] = new JRadioButton("Input-validating dialog " + "(with custom message area)");
    radioButtons[3].setActionCommand(customOptionCommand);

    radioButtons[4] = new JRadioButton("Non-modal dialog");
    radioButtons[4].setActionCommand(nonModalCommand);

    for (int i = 0; i < numButtons; i++) {
        group.add(radioButtons[i]);
    }
    radioButtons[0].setSelected(true);

    showItButton = new JButton("Show it!");
    showItButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String command = group.getSelection().getActionCommand();

            // pick one of many
            if (command == pickOneCommand) {
                Object[] possibilities = { "ham", "spam", "yam" };
                String s = (String) JOptionPane.showInputDialog(frame,
                        "Complete the sentence:\n" + "\"Green eggs and...\"", "Customized Dialog",
                        JOptionPane.PLAIN_MESSAGE, icon, possibilities, "ham");

                // If a string was returned, say so.
                if ((s != null) && (s.length() > 0)) {
                    setLabel("Green eggs and... " + s + "!");
                    return;
                }

                // If you're here, the return value was null/empty.
                setLabel("Come on, finish the sentence!");

                // text input
            } else if (command == textEnteredCommand) {
                String s = (String) JOptionPane.showInputDialog(frame,
                        "Complete the sentence:\n" + "\"Green eggs and...\"", "Customized Dialog",
                        JOptionPane.PLAIN_MESSAGE, icon, null, "ham");

                // If a string was returned, say so.
                if ((s != null) && (s.length() > 0)) {
                    setLabel("Green eggs and... " + s + "!");
                    return;
                }

                // If you're here, the return value was null/empty.
                setLabel("Come on, finish the sentence!");

                // non-auto-closing dialog
            } else if (command == nonAutoCommand) {
                final JOptionPane optionPane = new JOptionPane(
                        "The only way to close this dialog is by\n" + "pressing one of the following buttons.\n"
                                + "Do you understand?",
                        JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);

                // You can't use pane.createDialog() because that
                // method sets up the JDialog with a property change
                // listener that automatically closes the window
                // when a button is clicked.
                final JDialog dialog = new JDialog(frame, "Click a button", true);
                dialog.setContentPane(optionPane);
                dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                dialog.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent we) {
                        setLabel("Thwarted user attempt to close window.");
                    }
                });
                optionPane.addPropertyChangeListener(new PropertyChangeListener() {
                    public void propertyChange(PropertyChangeEvent e) {
                        String prop = e.getPropertyName();

                        if (dialog.isVisible() && (e.getSource() == optionPane)
                                && (JOptionPane.VALUE_PROPERTY.equals(prop))) {
                            // If you were going to check something
                            // before closing the window, you'd do
                            // it here.
                            dialog.setVisible(false);
                        }
                    }
                });
                dialog.pack();
                dialog.setLocationRelativeTo(frame);
                dialog.setVisible(true);

                int value = ((Integer) optionPane.getValue()).intValue();
                if (value == JOptionPane.YES_OPTION) {
                    setLabel("Good.");
                } else if (value == JOptionPane.NO_OPTION) {
                    setLabel("Try using the window decorations " + "to close the non-auto-closing dialog. "
                            + "You can't!");
                } else {
                    setLabel("Window unavoidably closed (ESC?).");
                }

                // non-auto-closing dialog with custom message area
                // NOTE: if you don't intend to check the input,
                // then just use showInputDialog instead.
            } else if (command == customOptionCommand) {
                customDialog.setLocationRelativeTo(frame);
                customDialog.setVisible(true);

                String s = customDialog.getValidatedText();
                if (s != null) {
                    // The text is valid.
                    setLabel("Congratulations!  " + "You entered \"" + s + "\".");
                }

                // non-modal dialog
            } else if (command == nonModalCommand) {
                // Create the dialog.
                final JDialog dialog = new JDialog(frame, "A Non-Modal Dialog");

                // Add contents to it. It must have a close button,
                // since some L&Fs (notably Java/Metal) don't provide one
                // in the window decorations for dialogs.
                JLabel label = new JLabel("<html><p align=center>" + "This is a non-modal dialog.<br>"
                        + "You can have one or more of these up<br>" + "and still use the main window.");
                label.setHorizontalAlignment(JLabel.CENTER);
                Font font = label.getFont();
                label.setFont(label.getFont().deriveFont(font.PLAIN, 14.0f));

                JButton closeButton = new JButton("Close");
                closeButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        dialog.setVisible(false);
                        dialog.dispose();
                    }
                });
                JPanel closePanel = new JPanel();
                closePanel.setLayout(new BoxLayout(closePanel, BoxLayout.LINE_AXIS));
                closePanel.add(Box.createHorizontalGlue());
                closePanel.add(closeButton);
                closePanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 5));

                JPanel contentPane = new JPanel(new BorderLayout());
                contentPane.add(label, BorderLayout.CENTER);
                contentPane.add(closePanel, BorderLayout.PAGE_END);
                contentPane.setOpaque(true);
                dialog.setContentPane(contentPane);

                // Show it.
                dialog.setSize(new Dimension(300, 150));
                dialog.setLocationRelativeTo(frame);
                dialog.setVisible(true);
            }
        }
    });

    return createPane(moreDialogDesc + ":", radioButtons, showItButton);
}

From source file:com.mirth.connect.client.ui.SettingsPanelServer.java

public void doRestore() {
    if (getFrame().isSaveEnabled()) {
        if (!getFrame().alertOkCancel(this, "Your new settings will first be saved.  Continue?")) {
            return;
        }//w  w w .j a  va2 s  .  c  o  m
        if (!doSave()) {
            return;
        }
    }

    String content = getFrame().browseForFileString("XML");

    if (content != null) {
        try {
            if (!getFrame().promptObjectMigration(content, "server configuration")) {
                return;
            }

            final ServerConfiguration configuration = ObjectXMLSerializer.getInstance().deserialize(content,
                    ServerConfiguration.class);

            final JCheckBox deployChannelsCheckBox = new JCheckBox("Deploy all channels after import");
            deployChannelsCheckBox.setSelected(true);
            String warningMessage = "Import configuration from " + configuration.getDate()
                    + "?\nWARNING: This will overwrite all current channels,\nalerts, server properties, and plugin properties.\n";
            Object[] params = { warningMessage, new JLabel(" "), deployChannelsCheckBox };
            int option = JOptionPane.showConfirmDialog(this, params, "Select an Option",
                    JOptionPane.YES_NO_OPTION);

            if (option == JOptionPane.YES_OPTION) {
                final Set<String> alertIds = new HashSet<String>();
                for (AlertStatus alertStatus : PlatformUI.MIRTH_FRAME.mirthClient.getAlertStatusList()) {
                    alertIds.add(alertStatus.getId());
                }

                final String workingId = getFrame().startWorking("Restoring server config...");

                SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

                    private boolean updateAlerts = false;

                    public Void doInBackground() {
                        try {
                            getFrame().mirthClient.setServerConfiguration(configuration,
                                    deployChannelsCheckBox.isSelected());
                            getFrame().channelPanel.clearChannelCache();
                            doRefresh();
                            getFrame().alertInformation(SettingsPanelServer.this,
                                    "Your configuration was successfully restored.");
                            updateAlerts = true;
                        } catch (ClientException e) {
                            getFrame().alertThrowable(SettingsPanelServer.this, e);
                        }
                        return null;
                    }

                    public void done() {
                        if (getFrame().alertPanel == null) {
                            getFrame().alertPanel = new DefaultAlertPanel();
                        }

                        if (updateAlerts) {
                            getFrame().alertPanel.updateAlertDetails(alertIds);
                        }
                        getFrame().stopWorking(workingId);
                    }
                };

                worker.execute();
            }
        } catch (Exception e) {
            getFrame().alertError(this, "Invalid server configuration file.");
        }
    }
}

From source file:com.firmansyah.imam.sewa.kendaraan.FormUser.java

private void btnHapusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHapusActionPerformed
    String id = inputIdUser.getText();
    System.out.println("Memilih ID : " + id);

    int dialogButton = JOptionPane.YES_NO_OPTION;
    int dialogResult;
    dialogResult = JOptionPane.showConfirmDialog(this, "Anda yakin Menghapus Data ini? ", "Konfirmasi",
            dialogButton);//from  www  .ja  va  2 s  .  c  o  m

    if (dialogResult == 0) {
        String url = Path.serverURL + "/user/delete/" + id;

        getDataURL dataurl = new getDataURL();

        try {
            String data = dataurl.getData(url);
            System.out.println(data);

            if (data.equals("1")) {
                JOptionPane.showMessageDialog(this, "Data Berhasil dihapus", "Informasi",
                        JOptionPane.INFORMATION_MESSAGE);

                System.out.println("Menghapus Data ID : " + id);
            } else {
                JOptionPane.showMessageDialog(this, "Data Tidak Berhasil dihapus", "Informasi",
                        JOptionPane.ERROR_MESSAGE);
            }

        } catch (IOException ex) {
            Logger.getLogger(FormUser.class.getName()).log(Level.SEVERE, null, ex);

            JOptionPane.showMessageDialog(this,
                    "Data Tidak Bisa dihapus\nKarena Memiliki Relasi dengan Data Lainnya", "Informasi",
                    JOptionPane.ERROR_MESSAGE);
        }
    } else {
        System.out.println("Tidak Menghapus : " + id);
    }

    // refresh form
    refreshForm();
}

From source file:Formulario.CapturaHuella.java

private void btnConfiguracionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConfiguracionActionPerformed
    // TODO add your handling code here:
    stop();/*w w w. ja va  2  s.  c  o  m*/

    int op = JOptionPane.showConfirmDialog(this,
            "No modifique estos parametros al menos que se requiera.\n" + "Desea configurar?",
            "Desea configurar?", JOptionPane.YES_NO_OPTION);
    if (op == JOptionPane.OK_OPTION) {
        //  Ingreso in=new Ingreso(this, true);
        try {

            new Ingreso(this, true).setVisible(true);
            dispose();

        } catch (Exception ex) {
            Logger.getLogger(CapturaHuella.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.biosis.biosislite.vistas.inventario.MantenimientoFactura.java

private void btneliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btneliminarActionPerformed
    // TODO add your handling code here:
    accion = AbstractControlador.ELIMINAR;
    if (tblFactura.getSelectedRow() != -1) {

        Integer codigo = tblFactura.getSelectedRow();

        Factura factura = facturaControlador.buscarPorId(lista.get(codigo).getId());

        if (factura != null) {
            if (JOptionPane.showConfirmDialog(null, "Desea Eliminar el Tipo?", "Mensaje del Sistema",
                    JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {

                int[] filas = tblFactura.getSelectedRows();
                for (int i = 0; i < filas.length; i++) {
                    Factura factura2 = lista.get(filas[0]);
                    lista.remove(factura2);
                    facturaControlador.setSeleccionado(factura2);
                    facturaControlador.accion(accion);
                }//from w  w  w  . j a v a2 s  .c  o  m
                if (facturaControlador.accion(accion) == 3) {
                    JOptionPane.showMessageDialog(null, "Tipo eliminado correctamente", "Mensaje del Sistema",
                            JOptionPane.INFORMATION_MESSAGE);

                } else {
                    JOptionPane.showMessageDialog(null, "Tipo no eliminada", "Mensaje del Sistema",
                            JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Tipo no eliminada", "Mensaje del Sistema",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    } else {
        JOptionPane.showMessageDialog(null, "Debe seleccionar un Tipo", "Mensaje del Sistema",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com._17od.upm.gui.DatabaseActions.java

public void deleteAccount() throws IOException, CryptoException, TransportException, ProblemReadingDatabaseFile,
        PasswordDatabaseException {/*  w  ww  .  j  av a  2s  .  co m*/

    if (getLatestVersionOfDatabase()) {
        SortedListModel listview = (SortedListModel) mainWindow.getAccountsListview().getModel();
        String selectedAccName = (String) mainWindow.getAccountsListview().getSelectedValue();

        int buttonSelected = JOptionPane.showConfirmDialog(mainWindow,
                Translator.translate("askConfirmDeleteAccount", selectedAccName),
                Translator.translate("confirmDeleteAccount"), JOptionPane.YES_NO_OPTION);
        if (buttonSelected == JOptionPane.OK_OPTION) {
            //Remove the account from the listview, accountNames arraylist & the database
            listview.removeElement(selectedAccName);
            int i = accountNames.indexOf(selectedAccName);
            accountNames.remove(i);
            database.deleteAccount(selectedAccName);
            saveDatabase();
            //[1375385] Call the filter method so that the listview is 
            //reinitialised with the remaining matching items
            filter();
        }
    }

}

From source file:com.proyecto.vista.MantenimientoUnidadMedida.java

private void btnguardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnguardarActionPerformed
    // TODO add your handling code here:
    String palabra = "";
    String palabra2 = "";
    if (accion == 1) {
        palabra = "registrar";
        palabra2 = "registrado";

        if (JOptionPane.showConfirmDialog(null, "Desea " + palabra + " la Unidad?", "Mensaje del Sistema",
                JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {

            unidadControlador.getSeleccionado().setNombre(nombreField.getText().toUpperCase());
            unidadControlador.getSeleccionado().setAbreviatura(abreviaturaField.getText().toUpperCase());

            unidadControlador.accion(accion);
            lista.add(unidadControlador.getSeleccionado());

            if (accion == 1) {
                JOptionPane.showMessageDialog(null, "Unidad " + palabra2 + " correctamente",
                        "Mensaje del Sistema", JOptionPane.INFORMATION_MESSAGE);
                FormularioUtil.limpiarComponente(panelDatos);
            } else {
                JOptionPane.showMessageDialog(null, "Unidad no " + palabra2, "Mensaje del Sistema",
                        JOptionPane.ERROR_MESSAGE);
            }/*from   w  ww .j  a v  a2 s  . c o  m*/
        } else {
            FormularioUtil.limpiarComponente(panelDatos);
            JOptionPane.showMessageDialog(null, "Unidad no " + palabra2, "Mensaje del Sistema",
                    JOptionPane.ERROR_MESSAGE);
        }
    } else if (accion == 2) {
        palabra = "modificar";
        palabra2 = "modificado";

        if (JOptionPane.showConfirmDialog(null, "Desea " + palabra + " la Unidad?", "Mensaje del Sistema",
                JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {

            if (accion == 2) {
                JOptionPane.showMessageDialog(null, "Unidad " + palabra2 + " correctamente",
                        "Mensaje del Sistema", JOptionPane.INFORMATION_MESSAGE);

                lista.clear();

                unidadControlador.getSeleccionado().setNombre(nombreField.getText().toUpperCase());
                unidadControlador.getSeleccionado().setAbreviatura(abreviaturaField.getText().toUpperCase());

                unidadControlador.accion(accion);
                listar();

                FormularioUtil.limpiarComponente(panelDatos);

            } else {
                JOptionPane.showMessageDialog(null, "Unidad no " + palabra2, "Mensaje del Sistema",
                        JOptionPane.ERROR_MESSAGE);
            }
        } else {
            FormularioUtil.limpiarComponente(panelDatos);
            JOptionPane.showMessageDialog(null, "Unidad no " + palabra2, "Mensaje del Sistema",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    FormularioUtil.activarComponente(panelOpciones, true);
    FormularioUtil.activarComponente(panelGuardar, false);
    FormularioUtil.activarComponente(panelDatos, false);

}

From source file:gdt.jgui.entity.index.JIndexPanel.java

/**
 * Get the context menu.//from w ww.  j a  va  2s  .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("IndexPanel:getConextMenu:menu selected");
            menu.removeAll();
            JMenuItem expandItem = new JMenuItem("Expand");
            expandItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    expandAll(tree, new TreePath(rootNode), true);
                }
            });
            menu.add(expandItem);
            JMenuItem collapseItem = new JMenuItem("Collapse");
            collapseItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    expandAll(tree, new TreePath(rootNode), false);
                }
            });
            menu.add(collapseItem);
            final TreePath[] tpa = tree.getSelectionPaths();
            if (tpa != null && tpa.length > 0) {
                menu.addSeparator();
                JMenuItem copyItem = new JMenuItem("Copy");
                copyItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        cut = false;
                        console.clipboard.clear();
                        DefaultMutableTreeNode node;
                        String locator$;
                        for (TreePath tp : tpa) {
                            node = (DefaultMutableTreeNode) tp.getLastPathComponent();
                            locator$ = (String) node.getUserObject();
                            if (locator$ != null)
                                console.clipboard.putString(locator$);
                        }
                    }
                });
                menu.add(copyItem);
                JMenuItem cutItem = new JMenuItem("Cut");
                cutItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        cut = true;
                        console.clipboard.clear();
                        DefaultMutableTreeNode node;
                        String locator$;
                        for (TreePath tp : tpa) {
                            node = (DefaultMutableTreeNode) tp.getLastPathComponent();
                            locator$ = (String) node.getUserObject();
                            if (locator$ != null)
                                console.clipboard.putString(locator$);
                        }
                    }
                });
                menu.add(cutItem);
                JMenuItem deleteItem = new JMenuItem("Delete");
                deleteItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        int response = JOptionPane.showConfirmDialog(console.getContentPanel(), "Delete ?",
                                "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                        if (response == JOptionPane.YES_OPTION) {
                            try {
                                DefaultMutableTreeNode node;
                                String locator$;
                                String nodeKey$;
                                for (TreePath tp : tpa) {
                                    node = (DefaultMutableTreeNode) tp.getLastPathComponent();
                                    locator$ = (String) node.getUserObject();
                                    nodeKey$ = Locator.getProperty(locator$, NODE_KEY);
                                    index.removeElementItem("index.title", nodeKey$);
                                    index.removeElementItem("index.jlocator", nodeKey$);
                                }
                                Entigrator entigrator = console.getEntigrator(entihome$);
                                entigrator.save(index);
                                JConsoleHandler.execute(console, getLocator());
                            } catch (Exception ee) {
                                LOGGER.info(ee.toString());
                            }
                        }
                    }
                });
                menu.add(deleteItem);
            }
        }

        @Override
        public void menuDeselected(MenuEvent e) {
        }

        @Override
        public void menuCanceled(MenuEvent e) {
        }
    });

    return menu;
}