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:condorclient.MainFXMLController.java

@FXML
void reScheduleFired(ActionEvent event) {
    //cluster?/*www . ja  v a2  s.  com*/
    int oldId = 0;//??
    int delNo = 0;
    int reScheduleId = 0;

    URL url = null;

    // String scheddURLStr="http://localhost:9628";
    XMLHandler handler = new XMLHandler();
    String scheddStr = handler.getURL("schedd");
    try {
        url = new URL(scheddStr);
    } catch (MalformedURLException e3) {
        // TODO Auto-generated catch block
        e3.printStackTrace();
    }
    Schedd schedd = null;

    int n = JOptionPane.showConfirmDialog(null, "?????", "",
            JOptionPane.YES_NO_OPTION);
    if (n == JOptionPane.YES_OPTION) {

        //checkboxclusterId
        System.out.print(Thread.currentThread().getName() + "\n");

        try {
            schedd = new Schedd(url);
        } catch (ServiceException ex) {
            Logger.getLogger(CondorClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        //ClassAdStructAttr[]

        ClassAd ad = null;//birdbath.ClassAd;
        ClassAdStructAttr[][] classAdArray = null;
        ClassAdStructAttr[][] classAdArray2 = null;
        String taskStatus = "";

        final List<?> selectedNodeList = new ArrayList<>(table.getSelectionModel().getSelectedItems());
        for (Object o : selectedNodeList) {
            if (o instanceof ObservableDisplayedClassAd) {
                oldId = Integer.parseInt(((ObservableDisplayedClassAd) o).getClusterId());
                taskStatus = ((ObservableDisplayedClassAd) o).getJobStatus();
                if (taskStatus.equals("") || taskStatus.equals("?") || taskStatus.equals("")) {
                    JOptionPane.showMessageDialog(null, "??????");
                    return;
                }

            }
        }
        //e
        int job = 0;
        Transaction xact = schedd.createTransaction();
        try {
            xact.begin(30);

        } catch (RemoteException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        System.out.println("oldId:" + oldId);

        String findreq = "owner==\"" + condoruser + "\"&&ClusterId==" + oldId;
        try {
            classAdArray = schedd.getJobAds(findreq);
            classAdArray2 = schedd.getJobAds(findreq);
        } catch (RemoteException ex) {
            Logger.getLogger(MainFXMLController.class.getName()).log(Level.SEVERE, null, ex);
        }
        //?jobclassAd?
        int newClusterId = 0;
        try {
            newClusterId = xact.createCluster();

        } catch (RemoteException e) {
        }
        int newJobId = 0;
        //            XMLHandler handler = new XMLHandler();
        String oldname = handler.getJobName("" + oldId);
        String transferInput = "";
        String jobdir = null;
        //?job??job
        int jobcount = 0;
        String timestamp = (new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date());
        System.out.println("oldname" + oldname);
        jobdir = handler.getTaskDir("" + oldId);
        String expfilename = handler.getExpFile("" + oldId);
        String infofilename = handler.getInfoFile("" + oldId);
        for (ClassAdStructAttr[] x : classAdArray) {

            ad = new ClassAd(x);
            job = Integer.parseInt(ad.get("ProcId"));
            ClassAdStructAttr[] attributes = null;// {new ClassAdStructAttr()};

            System.out.println("jobdir:===" + jobdir);

            //??
            // 
            File[] files = { new File(expfilename), new File(infofilename) };// new File[2];

            System.out.println(expfilename + "===" + infofilename);

            //
            String oldiwd = jobdir.substring(0, jobdir.length() - 14);//D:\tmp\test\dirtest\20140902200811;
            String resultdirstr = oldiwd + timestamp + "\\" + job;//job
            // new String(handler.getTaskDir(oldname).getBytes(),"UTF-8");
            //
            //attributes[0] = new ClassAdStructAttr("Iwd", ClassAdAttrType.value3, resultdirstr);
            File newjobdir = new File(resultdirstr);
            try {
                System.out.println("resultdirstr:" + resultdirstr);
                FileUtils.forceMkdir(newjobdir);
            } catch (IOException ex) {
                Logger.getLogger(CreateJobDialogController.class.getName()).log(Level.SEVERE, null, ex);
            }
            //?
            /* for (int j = 0; j < inputfilecount; j++) {
              System.out.println("j:" + j);
              try {
              FileUtils.copyFileToDirectory(files[j], newjobdir);
              } catch (IOException ex) {
              Logger.getLogger(MainFXMLController.class.getName()).log(Level.SEVERE, null, ex);
              }
              }*/

            try {
                newJobId = xact.createJob(newClusterId);
            } catch (RemoteException ex) {
                Logger.getLogger(MainFXMLController.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {

                xact.submit(newClusterId, newJobId, condoruser, UniverseType.VANILLA, ad.get("Cmd"),
                        ad.get("Arguments"), ad.get("Requirements"), attributes, files);
                xact.closeSpool(oldId, job);
            } catch (RemoteException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        //s
        try {
            xact.removeCluster(oldId, "");
        } catch (RemoteException ex) {
            Logger.getLogger(MainFXMLController.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            xact.commit();
        } catch (RemoteException e) {

            e.printStackTrace();
        }
        try {
            schedd.requestReschedule();
        } catch (RemoteException ex) {
            Logger.getLogger(MainFXMLController.class.getName()).log(Level.SEVERE, null, ex);
        }

        System.out.println("comit:" + oldname);

        String olddir = handler.getTaskDir("" + oldId);

        System.out.println("olddir:" + olddir);
        // olddir.substring(0, olddir.length() - 14);//??14?
        String newdir = olddir.substring(0, olddir.length() - 14) + timestamp;
        System.out.println("newdir:" + newdir);
        //  System.out.println(olddir+"\nmm"+newdir);
        handler.removeJob("" + oldId);
        handler.addJob(oldname, "" + newClusterId, newdir, expfilename, infofilename);

        // reConfigureButtons();
    } else if (n == JOptionPane.NO_OPTION) {
        System.out.println("qu xiao");

    }

    System.out.print("recreateTransaction succeed\n");

}

From source file:de.tor.tribes.ui.views.DSWorkbenchSOSRequestAnalyzer.java

private void copyDefRequests() {
    List<DefenseInformation> selection = getSelectedRows();

    if (selection.isEmpty()) {
        showInfo("Keine Eintrge gewhlt");
        return;//  w w  w.  j a v a 2  s  .com
    }
    boolean extended = (JOptionPaneHelper.showQuestionConfirmBox(this,
            "Erweiterte BB-Codes verwenden (nur fr Forum und Notizen geeignet)?", "Erweiterter BB-Code",
            "Nein", "Ja") == JOptionPane.YES_OPTION);

    SimpleDateFormat df = new SimpleDateFormat("dd.MM.yy HH:mm:ss");
    StringBuilder b = new StringBuilder();
    b.append(
            "Ich bentige die aufgelisteten oder vergleichbare Untersttzungen in den folgenden Drfern:\n\n");

    for (DefenseInformation defense : selection) {
        if (!defense.isSave()) {
            Village target = defense.getTarget();
            int needed = defense.getNeededSupports();
            int available = defense.getSupports().length;
            TroopAmountFixed split = DSWorkbenchSettingsDialog.getSingleton().getDefense();
            TroopAmountFixed need = new TroopAmountFixed();
            for (UnitHolder unit : DataHolder.getSingleton().getUnits()) {
                need.setAmountForUnit(unit, (needed - available) * split.getAmountForUnit(unit));
            }

            if (extended) {
                b.append("[table]\n");
                b.append("[**]").append(target.toBBCode()).append("[|]");
                b.append("[img]").append(UnitTableInterface.createDefenderUnitTableLink(need))
                        .append("[/img][/**]\n");
                b.append("[*]Angriffe/Fakes[|]").append(defense.getAttackCount()).append("/")
                        .append(defense.getFakeCount()).append("\n");
                b.append("[*]Zeitraum[|]").append(df.format(defense.getFirstAttack())).append(" bis ")
                        .append(df.format(defense.getLastAttack())).append("\n");
                b.append("[/table]\n");
            } else {
                b.append(buildSimpleRequestTable(target, need, defense));
            }
        }
    }
    try {
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(b.toString()), null);
        showSuccess("Untersttzungsanfragen in die Zwischenablage kopiert");
    } catch (HeadlessException hex) {
        showError("Fehler beim Kopieren in die Zwischenablage");
    }
}

From source file:edu.ku.brc.af.prefs.PreferencesDlg.java

@Override
public boolean closePrefs() {
    if (okBtn.isEnabled()) {
        Object[] options = { getResourceString("PrefsDlg.SAVE_PREFS"), //$NON-NLS-1$
                getResourceString("PrefsDlg.DONT_SAVE_PREFS"), //$NON-NLS-1$
                getResourceString("CANCEL") //$NON-NLS-1$
        };/*  w ww . ja  v  a 2  s . co  m*/
        int userChoice = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(),
                getResourceString("PrefsDlg.MSG"), //$NON-NLS-1$
                getResourceString("PREFERENCES"), //$NON-NLS-1$
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
        if (userChoice == JOptionPane.YES_OPTION) {
            okButtonPressed();

        } else if (userChoice == JOptionPane.NO_OPTION) {
            cancelButtonPressed();
        } else {
            return false;
        }
    } else {
        cancelButtonPressed();
    }
    return true;
}

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  ww  w  .  j  av  a  2s  .c o  m*/
                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: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;
        }/*from www.  j  a v  a 2 s  . co 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.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.ja v a2 s.  com*/
                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:es.emergya.ui.plugins.admin.aux1.RecursoDialog.java

public RecursoDialog(final Recurso rec, final AdminResources adminResources) {
    super();/*from   w w  w  .  j a  va  2  s.  c  om*/
    setAlwaysOnTop(true);
    setSize(600, 400);

    setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosing(WindowEvent e) {
            super.windowClosing(e);
            if (cambios) {
                int res = JOptionPane.showConfirmDialog(RecursoDialog.this,
                        "Existen cambios sin guardar. Seguro que desea cerrar la ventana?",
                        "Cambios sin guardar", JOptionPane.OK_CANCEL_OPTION);
                if (res != JOptionPane.CANCEL_OPTION) {
                    e.getWindow().dispose();
                }
            } else {
                e.getWindow().dispose();
            }
        }
    });
    final Recurso r = (rec == null) ? null : RecursoConsultas.get(rec.getId());
    if (r != null) {
        setTitle(i18n.getString("Resources.summary.titleWindow") + " " + r.getIdentificador());
    } else {
        setTitle(i18n.getString("Resources.summary.titleWindow.new"));
    }
    setIconImage(getBasicWindow().getFrame().getIconImage());
    JPanel base = new JPanel();
    base.setBackground(Color.WHITE);
    base.setLayout(new BoxLayout(base, BoxLayout.Y_AXIS));

    // Icono del titulo
    JPanel title = new JPanel(new FlowLayout(FlowLayout.LEADING));
    title.setOpaque(false);
    JLabel labelTitulo = null;
    if (r != null) {
        labelTitulo = new JLabel(i18n.getString("Resources.summary"),
                LogicConstants.getIcon("tittleficha_icon_recurso"), JLabel.LEFT);

    } else {
        labelTitulo = new JLabel(i18n.getString("Resources.cabecera.nuevo"),
                LogicConstants.getIcon("tittleficha_icon_recurso"), JLabel.LEFT);

    }
    labelTitulo.setFont(LogicConstants.deriveBoldFont(12f));
    title.add(labelTitulo);
    base.add(title);

    // Nombre
    JPanel mid = new JPanel(new SpringLayout());
    mid.setOpaque(false);
    mid.add(new JLabel(i18n.getString("Resources.name"), JLabel.RIGHT));
    final JTextField name = new JTextField(25);
    if (r != null) {
        name.setText(r.getNombre());
    }

    name.getDocument().addDocumentListener(changeListener);
    name.setEditable(r == null);
    mid.add(name);

    // patrullas
    final JLabel labelSquads = new JLabel(i18n.getString("Resources.squad"), JLabel.RIGHT);
    mid.add(labelSquads);
    List<Patrulla> pl = PatrullaConsultas.getAll();
    pl.add(0, null);
    final JComboBox squads = new JComboBox(pl.toArray());
    squads.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXXXXXXX");
    squads.addActionListener(changeSelectionListener);
    squads.setOpaque(false);
    labelSquads.setLabelFor(squads);
    if (r != null) {
        squads.setSelectedItem(r.getPatrullas());
    } else {
        squads.setSelectedItem(null);
    }
    squads.setEnabled((r != null && r.getHabilitado() != null) ? r.getHabilitado() : true);
    mid.add(squads);

    // // Identificador
    // mid.setOpaque(false);
    // mid.add(new JLabel(i18n.getString("Resources.identificador"),
    // JLabel.RIGHT));
    // final JTextField identificador = new JTextField("");
    // if (r != null) {
    // identificador.setText(r.getIdentificador());
    // }
    // identificador.getDocument().addDocumentListener(changeListener);
    // identificador.setEditable(r == null);
    // mid.add(identificador);
    // Espacio en blanco
    // mid.add(Box.createHorizontalGlue());
    // mid.add(Box.createHorizontalGlue());

    // Tipo
    final JLabel labelTipoRecursos = new JLabel(i18n.getString("Resources.type"), JLabel.RIGHT);
    mid.add(labelTipoRecursos);
    final JComboBox types = new JComboBox(RecursoConsultas.getTipos());
    labelTipoRecursos.setLabelFor(types);
    types.addActionListener(changeSelectionListener);
    if (r != null) {
        types.setSelectedItem(r.getTipo());
    } else {
        types.setSelectedItem(0);
    }
    // types.setEditable(true);
    types.setEnabled(true);
    mid.add(types);

    // Estado Eurocop
    mid.add(new JLabel(i18n.getString("Resources.status"), JLabel.RIGHT));
    final JTextField status = new JTextField();
    if (r != null && r.getEstadoEurocop() != null) {
        status.setText(r.getEstadoEurocop().getIdentificador());
    }
    status.setEditable(false);
    mid.add(status);

    // Subflota y patrulla
    mid.add(new JLabel(i18n.getString("Resources.subfleet"), JLabel.RIGHT));
    final JComboBox subfleets = new JComboBox(FlotaConsultas.getAllHabilitadas());
    subfleets.addActionListener(changeSelectionListener);
    if (r != null) {
        subfleets.setSelectedItem(r.getFlotas());
    } else {
        subfleets.setSelectedIndex(0);
    }
    subfleets.setEnabled(true);
    subfleets.setOpaque(false);
    mid.add(subfleets);

    // Referencia humana
    mid.add(new JLabel(i18n.getString("Resources.incidences"), JLabel.RIGHT));
    final JTextField rhumana = new JTextField();
    // if (r != null && r.getIncidencias() != null) {
    // rhumana.setText(r.getIncidencias().getReferenciaHumana());
    // }
    rhumana.setEditable(false);
    mid.add(rhumana);

    // dispositivo
    mid.add(new JLabel(i18n.getString("Resources.device"), JLabel.RIGHT));
    final PlainDocument plainDocument = new PlainDocument() {

        private static final long serialVersionUID = 4929271093724956016L;

        @Override
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            if (this.getLength() + str.length() <= LogicConstants.LONGITUD_ISSI) {
                super.insertString(offs, str, a);
            }
        }
    };
    final JTextField issi = new JTextField(plainDocument, "", LogicConstants.LONGITUD_ISSI);
    plainDocument.addDocumentListener(changeListener);
    issi.setEditable(true);
    mid.add(issi);
    mid.add(new JLabel(i18n.getString("Resources.enabled"), JLabel.RIGHT));
    final JCheckBox enabled = new JCheckBox("", true);
    enabled.addActionListener(changeSelectionListener);
    enabled.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            if (enabled.isSelected()) {
                squads.setSelectedIndex(0);
            }
            squads.setEnabled(enabled.isSelected());
        }
    });
    enabled.setEnabled(true);
    enabled.setOpaque(false);
    if (r != null) {
        enabled.setSelected(r.getHabilitado());
    } else {
        enabled.setSelected(true);
    }
    if (r != null && r.getDispositivo() != null) {
        issi.setText(
                StringUtils.leftPad(String.valueOf(r.getDispositivo()), LogicConstants.LONGITUD_ISSI, '0'));
    }

    mid.add(enabled);

    // Fecha ultimo gps
    mid.add(new JLabel(i18n.getString("Resources.lastPosition"), JLabel.RIGHT));
    JTextField lastGPS = new JTextField();
    final Date lastGPSDateForRecurso = HistoricoGPSConsultas.lastGPSDateForRecurso(r);
    if (lastGPSDateForRecurso != null) {
        lastGPS.setText(SimpleDateFormat.getDateTimeInstance().format(lastGPSDateForRecurso));
    }
    lastGPS.setEditable(false);
    mid.add(lastGPS);

    // Espacio en blanco
    mid.add(Box.createHorizontalGlue());
    mid.add(Box.createHorizontalGlue());

    // informacion adicional
    JPanel infoPanel = new JPanel(new SpringLayout());
    final JTextField info = new JTextField(25);
    info.getDocument().addDocumentListener(changeListener);
    infoPanel.add(new JLabel(i18n.getString("Resources.info")));
    infoPanel.add(info);
    infoPanel.setOpaque(false);
    info.setOpaque(false);
    SpringUtilities.makeCompactGrid(infoPanel, 1, 2, 6, 6, 6, 18);

    if (r != null) {
        info.setText(r.getInfoAdicional());
    } else {
        info.setText("");
    }
    info.setEditable(true);

    // Espacio en blanco
    mid.add(Box.createHorizontalGlue());
    mid.add(Box.createHorizontalGlue());

    SpringUtilities.makeCompactGrid(mid, 5, 4, 6, 6, 6, 18);
    base.add(mid);
    base.add(infoPanel);

    JPanel buttons = new JPanel();
    buttons.setOpaque(false);
    JButton accept = null;
    if (r == null) {
        accept = new JButton("Crear", LogicConstants.getIcon("button_crear"));
    } else {
        accept = new JButton("Guardar", LogicConstants.getIcon("button_save"));
    }
    accept.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                if (cambios || r == null || r.getId() == null) {
                    boolean shithappens = true;
                    if ((r == null || r.getId() == null)) { // Estamos
                        // creando
                        // uno nuevo
                        if (RecursoConsultas.alreadyExists(name.getText())) {
                            shithappens = false;
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.nombreUnico"));
                        } else if (issi.getText() != null && issi.getText().length() > 0 && StringUtils
                                .trimToEmpty(issi.getText()).length() != LogicConstants.LONGITUD_ISSI) {
                            JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString(Locale.ROOT,
                                    "admin.recursos.popup.error.faltanCifras", LogicConstants.LONGITUD_ISSI));
                            shithappens = false;
                        } else if (issi.getText() != null && issi.getText().length() > 0
                                && LogicConstants.isNumeric(issi.getText())
                                && RecursoConsultas.alreadyExists(new Integer(issi.getText()))) {
                            shithappens = false;
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.dispositivoUnico"));
                        }
                    }
                    if (shithappens) {
                        if (name.getText().isEmpty()) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.nombreNulo"));
                        } else if (issi.getText() != null && issi.getText().length() > 0 && StringUtils
                                .trimToEmpty(issi.getText()).length() != LogicConstants.LONGITUD_ISSI) {
                            JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString(Locale.ROOT,
                                    "admin.recursos.popup.error.faltanCifras", LogicConstants.LONGITUD_ISSI));
                        } else if (issi.getText() != null && issi.getText().length() > 0
                                && LogicConstants.isNumeric(issi.getText()) && r != null && r.getId() != null
                                && RecursoConsultas.alreadyExists(new Integer(issi.getText()), r.getId())) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.issiUnico"));
                        } else if (issi.getText() != null && issi.getText().length() > 0
                                && !LogicConstants.isNumeric(issi.getText())) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.noNumerico"));
                            // } else if (identificador.getText().isEmpty())
                            // {
                            // JOptionPane
                            // .showMessageDialog(
                            // RecursoDialog.this,
                            // i18n.getString("admin.recursos.popup.error.identificadorNulo"));
                        } else if (subfleets.getSelectedIndex() == -1) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.noSubflota"));
                        } else if (types.getSelectedItem() == null
                                || types.getSelectedItem().toString().trim().isEmpty()) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.noTipo"));
                        } else {
                            int i = JOptionPane.showConfirmDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.dialogo.guardar.titulo"),
                                    i18n.getString("admin.recursos.popup.dialogo.guardar.guardar"),
                                    JOptionPane.YES_NO_CANCEL_OPTION);

                            if (i == JOptionPane.YES_OPTION) {

                                Recurso recurso = r;

                                if (r == null) {
                                    recurso = new Recurso();
                                }

                                recurso.setInfoAdicional(info.getText());
                                if (issi.getText() != null && issi.getText().length() > 0) {
                                    recurso.setDispositivo(new Integer(issi.getText()));
                                } else {
                                    recurso.setDispositivo(null);
                                }
                                recurso.setFlotas(FlotaConsultas.find(subfleets.getSelectedItem().toString()));
                                if (squads.getSelectedItem() != null && enabled.isSelected()) {
                                    recurso.setPatrullas(
                                            PatrullaConsultas.find(squads.getSelectedItem().toString()));
                                } else {
                                    recurso.setPatrullas(null);
                                }
                                recurso.setNombre(name.getText());
                                recurso.setHabilitado(enabled.isSelected());
                                // recurso.setIdentificador(identificador
                                // .getText());
                                recurso.setTipo(types.getSelectedItem().toString());
                                dispose();

                                RecursoAdmin.saveOrUpdate(recurso);
                                adminResources.refresh(null);

                                PluginEventHandler.fireChange(adminResources);
                            } else if (i == JOptionPane.NO_OPTION) {
                                dispose();
                            }
                        }
                    }
                } else {
                    log.debug("No hay cambios");
                    dispose();
                }

            } catch (Throwable t) {
                log.error("Error guardando un recurso", t);
            }
        }
    });
    buttons.add(accept);

    JButton cancelar = new JButton("Cancelar", LogicConstants.getIcon("button_cancel"));

    cancelar.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (cambios) {
                if (JOptionPane.showConfirmDialog(RecursoDialog.this,
                        "Existen cambios sin guardar. Seguro que desea cerrar la ventana?",
                        "Cambios sin guardar", JOptionPane.OK_CANCEL_OPTION) != JOptionPane.CANCEL_OPTION) {
                    dispose();
                }
            } else {
                dispose();
            }
        }
    });

    buttons.add(cancelar);

    base.add(buttons);

    getContentPane().add(base);
    setLocationRelativeTo(null);
    cambios = false;
    if (r == null) {
        cambios = true;
    }

    pack();

    int x;
    int y;

    Container myParent = getBasicWindow().getPluginContainer().getDetachedTab(0);
    Point topLeft = myParent.getLocationOnScreen();
    Dimension parentSize = myParent.getSize();

    Dimension mySize = getSize();

    if (parentSize.width > mySize.width) {
        x = ((parentSize.width - mySize.width) / 2) + topLeft.x;
    } else {
        x = topLeft.x;
    }

    if (parentSize.height > mySize.height) {
        y = ((parentSize.height - mySize.height) / 2) + topLeft.y;
    } else {
        y = topLeft.y;
    }

    setLocation(x, y);
    cambios = false;
}

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);
            }//  w  w w  . ja va 2s .co  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  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("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;
}

From source file:UserInterface.FinanceRole.DonateToPoorPeopleJPanel.java

private void donateJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_donateJButtonActionPerformed

    //Validation/* w  w w.  j a va 2 s . co  m*/
    boolean validationSuccess;
    validationSuccess = validation();

    if (validationSuccess) {

        Person objPPPerson = null;
        UserAccount objPPUserAccount = null;

        int selectedPP = poorPeopleJTable.getSelectedRow();

        if (selectedPP < 0) {
            JOptionPane.showMessageDialog(null, "Please select a Person");
            return;
        }

        objPPUserAccount = (UserAccount) poorPeopleJTable.getValueAt(selectedPP, 2);

        if (objPPUserAccount != null) {
            objPPPerson = objPPUserAccount.getObjPerson();

            objWorldEnterprise.getObjTransactionDirectory().updateTransactionAccount();

            BigDecimal worldBalance = objWorldEnterprise.getObjTransactionDirectory().getAvailableRealBalance();

            int positiveWorldBalance = worldBalance.compareTo(donationAmount);

            if (positiveWorldBalance >= 1) {

                int response = JOptionPane.showConfirmDialog(null,
                        "Total donation of $ " + donationAmount + "/- Do you want to Donate?", "Confirm",
                        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                if (response == JOptionPane.YES_OPTION) {

                    //PoorPeople Transaction
                    Transaction objVirtualPPTransaction = (Transaction) objPPPerson
                            .getObjPoorPeopleTransactionDirectory().addNewTransaction();
                    objVirtualPPTransaction
                            .setTransactionBDAmount(new BigDecimal(donationAmountJTextField.getText()));
                    objVirtualPPTransaction.setObjUserAccountSource(objUserAccount);
                    objVirtualPPTransaction.setObjUserAccountDestination(objPPUserAccount);
                    objVirtualPPTransaction.setTransactionSource(
                            Transaction.TransactionSourceType.FromWorldEnterprise.getValue());
                    objVirtualPPTransaction.setTransactionDestination(
                            Transaction.TransactionSourceType.ToPoorPeople.getValue());
                    objVirtualPPTransaction.setTransactionType(Transaction.TransactionType.Credit.getValue());
                    objVirtualPPTransaction
                            .setTransactionMode(Transaction.TransactionModeType.Virtual.getValue());
                    objPPPerson.getObjPoorPeopleTransactionDirectory().updateTransactionAccount();

                    //WorldEnterprise Transaction
                    Transaction objVirtualWETransaction = (Transaction) objWorldEnterprise
                            .getObjTransactionDirectory().addNewTransaction();
                    objVirtualWETransaction
                            .setTransactionBDAmount(new BigDecimal(donationAmountJTextField.getText()));
                    objVirtualWETransaction.setObjUserAccountSource(objUserAccount);
                    objVirtualWETransaction.setObjUserAccountDestination(objPPUserAccount);
                    objVirtualWETransaction.setTransactionSource(
                            Transaction.TransactionSourceType.FromWorldEnterprise.getValue());
                    objVirtualWETransaction.setTransactionDestination(
                            Transaction.TransactionSourceType.ToPoorPeople.getValue());
                    objVirtualWETransaction.setTransactionType(Transaction.TransactionType.Debit.getValue());
                    objVirtualWETransaction
                            .setTransactionMode(Transaction.TransactionModeType.Virtual.getValue());
                    objWorldEnterprise.getObjTransactionDirectory().updateTransactionAccount();

                    JOptionPane.showMessageDialog(null, "$ " + donationAmount + "/- donated successfully");

                    //DonationGivenRecords
                    String donationLogs = objVirtualWETransaction.getTransactionID() + ","
                            + objVirtualWETransaction.getTransactionBDAmount() + ","
                            + objVirtualWETransaction.getObjUserAccountSource() + ","
                            + objVirtualWETransaction.getTransactionSource() + ","
                            + objVirtualWETransaction.getObjUserAccountDestination() + ","
                            + objVirtualWETransaction.getTransactionDestination() + ","
                            + objVirtualWETransaction.getTransactionType() + ","
                            + objVirtualWETransaction.getTransactionMode();

                    GenerateReports.donationGivenRecords(donationLogs);

                    donationAmountJTextField.setText(null);

                    populateTransactionTable(objPPPerson);
                }
            } else {
                JOptionPane.showMessageDialog(null, "World Balance is low");
            }
        } else {
            JOptionPane.showMessageDialog(null, "Please select again");
        }
    }
}