Example usage for javax.swing JOptionPane showOptionDialog

List of usage examples for javax.swing JOptionPane showOptionDialog

Introduction

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

Prototype

@SuppressWarnings("deprecation")
public static int showOptionDialog(Component parentComponent, Object message, String title, int optionType,
        int messageType, Icon icon, Object[] options, Object initialValue) throws HeadlessException 

Source Link

Document

Brings up a dialog with a specified icon, where the initial choice is determined by the initialValue parameter and the number of choices is determined by the optionType parameter.

Usage

From source file:com.sec.ose.osi.ui.frm.main.identification.stringmatch.JPanStringMatchMain.java

public UEStringMatch exportUIEntity(String projectName) {

    String stringSearch = "";
    String componentName = "";
    String versionName = "";
    String licenseName = "";
    String newComponentName = "";
    String newVersionName = "";
    String newLicenseName = getSelectedLicenseName();

    log.debug("exportUIEntity - ");
    SelectedFilePathInfo selectedPaths = IdentifyMediator.getInstance().getSelectedFilePathInfo();
    JTableMatchedInfoForSM jTableMatchedInfoForSM = jPanelTableCardLayout.getSelectedTable();

    int row = jTableMatchedInfoForSM.getSelectedRow();

    int pathType = selectedPaths.getPathType();
    switch (pathType) {
    case SelectedFilePathInfo.SINGLE_FILE_TYPE: {
        stringSearch = String//  w w  w .  j  a  v a 2s .co m
                .valueOf(jTableMatchedInfoForSM.getValueAt(row, TableModelForSMFile.COL_STRING_SEARCH));
        componentName = String
                .valueOf(jTableMatchedInfoForSM.getValueAt(row, TableModelForSMFile.COL_COMPONENT_NAME));
        versionName = String
                .valueOf(jTableMatchedInfoForSM.getValueAt(row, TableModelForSMFile.COL_VERSION_NAME));
        licenseName = String
                .valueOf(jTableMatchedInfoForSM.getValueAt(row, TableModelForSMFile.COL_LICENSE_NAME));
    }
        break;
    case SelectedFilePathInfo.MULTIPLE_FILE_TYPE: {
    }
        break;
    case SelectedFilePathInfo.FOLDER_TYPE:
    case SelectedFilePathInfo.PROJECT_TYPE: {
        stringSearch = String
                .valueOf(jTableMatchedInfoForSM.getValueAt(row, TableModelForSMFolder.COL_STRING_SEARCH));
        componentName = String
                .valueOf(jTableMatchedInfoForSM.getValueAt(row, TableModelForSMFolder.COL_COMPONENT_NAME));
        versionName = String
                .valueOf(jTableMatchedInfoForSM.getValueAt(row, TableModelForSMFolder.COL_VERSION_NAME));
        licenseName = String
                .valueOf(jTableMatchedInfoForSM.getValueAt(row, TableModelForSMFile.COL_LICENSE_NAME));
    }
        break;
    }

    if (stringSearch.equals("null"))
        stringSearch = "";
    if (componentName.equals("null"))
        componentName = "";
    if (versionName.equals("null"))
        versionName = "";
    if (licenseName.equals("null"))
        licenseName = "";
    String status = String.valueOf(jTableMatchedInfoForSM.getValueAt(row, TableModelForSMFile.COL_STATUS));
    if (opt1ThisFileIs.isSelected()) {
        if (("Pending".equals(status))
                && (getSelectedLicenseName() == null || getSelectedLicenseName().length() <= 0)) {
            JOptionPane.showOptionDialog(null, "\"License\" Field must be non-empty.", "Pending identification",
                    JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE, null, buttonOK, "OK");
            return null;
        }

        if ((getSelectedComponentName()).length() > 0) {
            newComponentName = getSelectedComponentName();
        } else {
            newComponentName = "DECLARED_STRING_MATCH_LICENSE_" + newLicenseName;
        }
    } else if (opt2ThisFileContains.isSelected()) {
        if (("Pending".equals(status))
                && (getSelectedLicenseName() == null || getSelectedLicenseName().length() <= 0)) {
            JOptionPane.showOptionDialog(null, "\"Representative License\" Field must be non-empty.",
                    "Pending identification", JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE, null, buttonOK,
                    "OK");
            return null;
        }
        newComponentName = "DECLARED_STRING_MATCH_MULTIPLE_LICENSE_" + newLicenseName;
    }
    log.debug("exportUIEntity - newComponentName : " + newComponentName);

    UEStringMatch xUEStringMatch = new UEStringMatch(stringSearch, componentName, versionName, licenseName,
            newComponentName, newVersionName, newLicenseName);

    return xUEStringMatch;
}

From source file:edu.ku.brc.ui.UIRegistry.java

/**
 * Asks Yes, No, Cancel question using a JOptionPane
 * @param yesKey the resource key for the Yes button
 * @param noKey the resource key for the No button
 * @param cancelKey the resource key for the Cancel button
 * @param nonL10NMsg the message or question NOT Localized
 * @param titleKey the resource key for the Dialog Title
 * @return JOptionPane.NO_OPTION or JOptionPane.YES_OPTION
 *//*from  w  ww  .j  a  v a2s.  c  o  m*/
public static int askYesNoLocalized(final String yesKey, final String noKey, final String cancelKey,
        final String nonL10NMsg, final String titleKey) {
    int userChoice = JOptionPane.CANCEL_OPTION;
    Object[] options = { getResourceString(yesKey), getResourceString(noKey), getResourceString(cancelKey) };

    userChoice = JOptionPane.showOptionDialog(UIRegistry.getMostRecentWindow(), nonL10NMsg,
            getResourceString(titleKey), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null,
            options, options[0]);
    return userChoice;
}

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

public void importAccounts() throws TransportException, ProblemReadingDatabaseFile, IOException,
        CryptoException, PasswordDatabaseException {
    if (getLatestVersionOfDatabase()) {
        // Prompt for the file to import
        JFileChooser fc = new JFileChooser();
        fc.setDialogTitle(Translator.translate("import"));
        int returnVal = fc.showOpenDialog(mainWindow);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File csvFile = fc.getSelectedFile();

            // Unmarshall the accounts from the CSV file
            try {
                AccountsCSVMarshaller marshaller = new AccountsCSVMarshaller();
                ArrayList accountsInCSVFile = marshaller.unmarshal(csvFile);
                ArrayList accountsToImport = new ArrayList();

                boolean importCancelled = false;
                // Add each account to the open database. If the account
                // already exits the prompt to overwrite
                for (int i = 0; i < accountsInCSVFile.size(); i++) {
                    AccountInformation importedAccount = (AccountInformation) accountsInCSVFile.get(i);
                    if (database.getAccount(importedAccount.getAccountName()) != null) {
                        Object[] options = { "Overwrite Existing", "Keep Existing", "Cancel" };
                        int answer = JOptionPane.showOptionDialog(mainWindow,
                                Translator.translate("importExistingQuestion",
                                        importedAccount.getAccountName()),
                                Translator.translate("importExistingTitle"), JOptionPane.YES_NO_CANCEL_OPTION,
                                JOptionPane.QUESTION_MESSAGE, null, options, options[1]);

                        if (answer == 1) {
                            continue; // If keep existing then continue to the next iteration
                        } else if (answer == 2) {
                            importCancelled = true;
                            break; // Cancel the import
                        }//www  .j  a v  a 2  s  .co m
                    }

                    accountsToImport.add(importedAccount);
                }

                if (!importCancelled && accountsToImport.size() > 0) {
                    for (int i = 0; i < accountsToImport.size(); i++) {
                        AccountInformation accountToImport = (AccountInformation) accountsToImport.get(i);
                        database.deleteAccount(accountToImport.getAccountName());
                        database.addAccount(accountToImport);
                    }
                    saveDatabase();
                    accountNames = getAccountNames();
                    filter();
                }

            } catch (ImportException e) {
                JOptionPane.showMessageDialog(mainWindow, e.getMessage(),
                        Translator.translate("problemImporting"), JOptionPane.ERROR_MESSAGE);
            } catch (IOException e) {
                JOptionPane.showMessageDialog(mainWindow, e.getMessage(),
                        Translator.translate("problemImporting"), JOptionPane.ERROR_MESSAGE);
            } catch (CryptoException e) {
                JOptionPane.showMessageDialog(mainWindow, e.getMessage(),
                        Translator.translate("problemImporting"), JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}

From source file:pi.bestdeal.gui.InterfacePrincipale.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    int idd = (int) jTable3.getModel().getValueAt(jTable3.getSelectedRow(), 0);
    ChoixStat1 chStat = new ChoixStat1();
    ChoixStat2 chStat2 = new ChoixStat2();

    Object[] options = { "BACK", "NEXT" };
    int a = JOptionPane.showOptionDialog(null, chStat, "", JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.WARNING_MESSAGE, null, options, options[0]);
    int b = 0;/*from  ww  w .  j  a v a2 s . c  om*/
    if (chStat.jRadiosexe.isSelected() && chStat.jRadioconsult.isSelected()) {
        b = 0;
    }
    if (chStat.jRadiosexe.isSelected() && chStat.jRadiores.isSelected()) {
        b = 1;
    }
    if (chStat.jRadiooperation.isSelected() && chStat.jRadioconsult.isSelected()) {
        b = 2;
    }
    if (chStat.jRadiooperation.isSelected() && chStat.jRadiores.isSelected()) {
        b = 3;
    }
    if (a == 1 && b == 2) {
        chStat.setVisible(false);
        Object[] options2 = { "Annuler", "Afficher la Statistique" };
        int c = JOptionPane.showOptionDialog(null, chStat2, "", JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.WARNING_MESSAGE, null, options2, options[0]);
        if (c == 1) {
            java.util.Date d1 = chStat2.jDateDebut.getCalendar().getTime();
            java.sql.Date sqlDate = new java.sql.Date(d1.getTime());
            java.util.Date d2 = chStat2.jDatefin.getCalendar().getTime();
            java.sql.Date sqlDate2 = new java.sql.Date(d2.getTime());
            Charts charts = new Charts();

            XYSeriesCollection dataxy = charts.createDataset(sqlDate.toString(), sqlDate2.toString(), idd);
            final JFreeChart chart = ChartFactory.createXYLineChart(
                    "Evolution des Consultation par rapport au temps", "Jours", "Nombre des Consultations", //
                    dataxy, // Dataset
                    PlotOrientation.VERTICAL, // 

                    true, true, false);
            XYItemRenderer rend = chart.getXYPlot().getRenderer();

            ChartPanel crepart = new ChartPanel(chart);
            Plot plot = chart.getPlot();

            JPanel jpan = new JPanel();
            JButton button = new JButton("Sauvegarder");
            button.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        JFileChooser chooser = new JFileChooser();
                        chooser.showSaveDialog(jPanel3);
                        String path = chooser.getSelectedFile().getPath();
                        if ((!path.contains("jpg")) || (!path.contains("png")) || (!path.contains("jpeg"))) {
                            path = path + ".png";
                        }
                        File f = new File(path);
                        ChartUtilities.saveChartAsPNG(new File(path), chart, 800, 600);

                        if (f.exists() && !f.isDirectory()) {
                            JOptionPane.showMessageDialog(null, "Sauvegarde Effectue");
                            Desktop.getDesktop().open(f);
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });

            jpan.add(crepart);
            jpan.add(button);
            JOptionPane.showConfirmDialog(null, jpan, "Chart d'volution des consultations",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        }
    }
    if (a == 1 && (b == 3)) {
        Object[] options2 = { "Annuler", "Afficher la Statistique" };
        int c = JOptionPane.showOptionDialog(null, chStat2, "", JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.WARNING_MESSAGE, null, options2, options[0]);
        if (c == 1) {
            java.util.Date d1 = chStat2.jDateDebut.getCalendar().getTime();
            java.sql.Date sqlDate = new java.sql.Date(d1.getTime());
            java.util.Date d2 = chStat2.jDatefin.getCalendar().getTime();
            java.sql.Date sqlDate2 = new java.sql.Date(d2.getTime());
            Charts charts = new Charts();
            //     JFreeChart chrt = ChartFactory.createXYStepAreaChart(null, null, null, null, PlotOrientation.HORIZONTAL, rootPaneCheckingEnabled, rootPaneCheckingEnabled, rootPaneCheckingEnabled)
            XYSeriesCollection dataxy = charts.createDatasetRes(sqlDate.toString(), sqlDate2.toString(), idd);
            final JFreeChart chart = ChartFactory.createXYLineChart(
                    "Evolution des Consultation par rapport au temps", "Jours", "Nombre des Reservations",
                    dataxy, PlotOrientation.VERTICAL, true, true, false);
            XYItemRenderer rend = chart.getXYPlot().getRenderer();

            ChartPanel crepart = new ChartPanel(chart);
            Plot plot = chart.getPlot();

            JPanel jpan = new JPanel();
            jpan.setLayout(new FlowLayout(FlowLayout.LEADING));
            JButton button = new JButton();

            button.setText("Sauvegarder");
            button.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        JFileChooser chooser = new JFileChooser();
                        chooser.showSaveDialog(jPanel3);
                        String path = chooser.getSelectedFile().getPath();
                        if ((!path.contains("jpg")) || (!path.contains("png")) || (!path.contains("jpeg"))) {
                            path = path + ".png";
                        }
                        File f = new File(path);
                        ChartUtilities.saveChartAsPNG(new File(path), chart, 800, 600);

                        if (f.exists() && !f.isDirectory()) {
                            JOptionPane.showMessageDialog(null, "Sauvegarde Effectue");
                            Desktop.getDesktop().open(f);
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });

            jpan.add(crepart);
            jpan.add(button);
            JOptionPane.showConfirmDialog(null, jpan, "Test", JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.PLAIN_MESSAGE);
        }

    }
    if (a == 1 && b == 0) {
        ConsultationDAO cdao = ConsultationDAO.getInstance();
        DefaultPieDataset union = new DefaultPieDataset();
        union.setValue("Homme", cdao.consultationCounterByGender(false, idd));
        union.setValue("Femme", cdao.consultationCounterByGender(true, idd));

        final JFreeChart repart = ChartFactory.createPieChart3D("Rpartition par Sexe", union, true, true,
                false);
        ChartPanel crepart = new ChartPanel(repart);
        Plot plot = repart.getPlot();
        JPanel jpan = new JPanel();
        JButton button = new JButton("Sauvegarder");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    JFileChooser chooser = new JFileChooser();
                    chooser.showSaveDialog(jPanel3);
                    String path = chooser.getSelectedFile().getPath();
                    if ((!path.contains("jpg")) || (!path.contains("png")) || (!path.contains("jpeg"))) {
                        path = path + ".png";
                    }
                    File f = new File(path);
                    ChartUtilities.saveChartAsPNG(new File(path), repart, 800, 600);

                    if (f.exists() && !f.isDirectory()) {
                        JOptionPane.showMessageDialog(null, "Sauvegarde Effectue");
                        Desktop.getDesktop().open(f);
                    }
                } catch (IOException ex) {
                    Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

        jpan.add(crepart);
        jpan.add(button);
        JOptionPane.showConfirmDialog(null, jpan, "", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

    }
    if (a == 1 && b == 1) {
        DefaultPieDataset union = new DefaultPieDataset();
        ReservationDAO dAO = ReservationDAO.getInstance();
        union.setValue("Homme", dAO.reservationCounterByGender(false, idd));
        union.setValue("Femme", dAO.reservationCounterByGender(true, idd));

        final JFreeChart repart = ChartFactory.createPieChart3D("Rpartition par Sexe", union, true, true,
                false);
        ChartPanel crepart = new ChartPanel(repart);
        Plot plot = repart.getPlot();
        JPanel jpan = new JPanel();
        JButton button = new JButton("Sauvegarder");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    JFileChooser chooser = new JFileChooser();
                    chooser.showSaveDialog(jPanel3);
                    String path = chooser.getSelectedFile().getPath();
                    if ((!path.contains("jpg")) || (!path.contains("png")) || (!path.contains("jpeg"))) {
                        path = path + ".png";
                    }
                    File f = new File(path);
                    ChartUtilities.saveChartAsPNG(new File(path), repart, 800, 600);

                    if (f.exists() && !f.isDirectory()) {
                        JOptionPane.showMessageDialog(null, "Sauvegarde Effectue");
                        Desktop.getDesktop().open(f);
                    }
                } catch (IOException ex) {
                    Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

        jpan.add(crepart);
        jpan.add(button);
        JOptionPane.showConfirmDialog(null, jpan, "Chart de la rpartition des achat par sexe",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

    }
}

From source file:com.g2inc.scap.editor.gui.windows.EditorMainWindow.java

@Override
public void windowClosing(WindowEvent arg0) {
    // save window location and bounds
    Point myLocation = getLocation();
    Dimension mySize = getSize();

    guiProps.setProperty(EditorConfiguration.PROPERTY_MAIN_WINDOW_LOCATION_X, myLocation.x + "");
    guiProps.setProperty(EditorConfiguration.PROPERTY_MAIN_WINDOW_LOCATION_Y, myLocation.y + "");

    guiProps.setProperty(EditorConfiguration.PROPERTY_MAIN_WINDOW_SIZE_X, mySize.width + "");
    guiProps.setProperty(EditorConfiguration.PROPERTY_MAIN_WINDOW_SIZE_Y, mySize.height + "");

    guiProps.save();/*from ww  w.j  a v  a  2s .com*/

    // cycle through open internal frames(documents)
    // and see if any of them need to be saved
    JInternalFrame[] openFrames = desktopPane.getAllFrames();

    if (openFrames != null && openFrames.length > 0) {
        for (int x = 0; x < openFrames.length; x++) {
            JInternalFrame internalWin = openFrames[x];
            if (internalWin instanceof EditorForm) {
                EditorForm ef = (EditorForm) internalWin;
                if (ef.getDocument() == null) {
                    continue;
                }

                String filename = ef.getDocument().getFilename();

                if (filename == null) {
                    continue;
                }

                if (ef.isDirty()) {
                    Object[] options = { EditorMessages.FILE_CHOOSER_BUTTON_TEXT_SAVE, "Discard" };

                    String message = filename
                            + " has unsaved changes.  Do you want to save or discard changes?";
                    String dTitle = "Unsaved changes";

                    int n = JOptionPane.showOptionDialog(this, message, dTitle, JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE, null, options, options[0]);

                    if (n == JOptionPane.DEFAULT_OPTION || n == JOptionPane.YES_OPTION) {
                        final GenericProgressDialog progress = new GenericProgressDialog(
                                EditorMainWindow.getInstance(), true);
                        progress.setMessage("Saving changes to " + ef.getDocument().getFilename());
                        try {
                            final SCAPDocument sdoc = (SCAPDocument) ef.getDocument();

                            Runnable r = new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        sdoc.save();
                                    } catch (Exception e) {
                                        progress.setException(e);
                                    }
                                }
                            };

                            progress.setRunnable(r);

                            progress.pack();
                            progress.setLocationRelativeTo(this);
                            progress.setVisible(true);

                            if (progress.getException() != null) {
                                throw (progress.getException());
                            }

                            ef.setDirty(false);
                        } catch (Exception e) {
                            LOG.error("Error saving file " + filename, e);
                            String errMessage = filename + " couldn't be saved.  An error occured: "
                                    + e.getMessage();
                            dTitle = "File save error";

                            EditorUtil.showMessageDialog(this, errMessage, dTitle, JOptionPane.ERROR_MESSAGE);
                        }
                    }
                }
            }
        }
    }
}

From source file:edu.ku.brc.specify.tasks.SystemSetupTask.java

/**
 * Launches dialog for Importing and Exporting Forms and Resources.
 *///from www . ja  va2  s .co  m
public static boolean askBeforeStartingTool() {
    if (SubPaneMgr.getInstance().aboutToShutdown()) {
        Object[] options = { getResourceString("CONTINUE"), //$NON-NLS-1$
                getResourceString("CANCEL") //$NON-NLS-1$
        };
        return JOptionPane.YES_OPTION == JOptionPane.showOptionDialog(getTopWindow(),
                getLocalizedMessage(getI18NKey("REI_MSG")), //$NON-NLS-1$
                getResourceString(getI18NKey("REI_TITLE")), //$NON-NLS-1$
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
    }
    return false;
}

From source file:corelyzer.ui.CorelyzerApp.java

private void onDeleteSelectedSections(final int[] rows) {
    String mesg = "Are you sure you want to remove all\n" + "selected sections?";

    Object[] options = { "Cancel", "Yes" };
    int ans = JOptionPane.showOptionDialog(app.getMainFrame(), mesg, "Confirmation", JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, options, options[0]);

    if (ans == 1) {
        CoreGraph cg = CoreGraph.getInstance();
        TrackSceneNode t = cg.getCurrentTrack();

        if (t != null) {
            int tid = t.getId();

            // delete in reverse order
            for (int i = rows.length - 1; i >= 0; i--) {
                int row = rows[i];

                CoreSection cs = t.getCoreSection(row);
                if (cs != null) {
                    int csid = cs.getId();
                    controller.deleteSection(tid, csid);
                }//  w ww  . j  a  va 2s .co m
            }
        }
    }
}

From source file:edu.ku.brc.af.tasks.BaseTask.java

/**
 * Asks where the source of the COs should come from.
 * (This needs to be moved to the BaseTask in specify package)
 * @return the source enum//from w  ww .j a  v  a2  s . c o  m
 */
public ASK_TYPE askSourceOfObjects(final Class<? extends FormDataObjIFace> classForSrc) {
    Object[] options = { getResourceString("NEW_BT_USE_RS"),
            getResourceString("NEW_BT_ENTER_" + classForSrc.getSimpleName()) };
    int userChoice = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(),
            getResourceString("NEW_BT_CHOOSE_RS_" + classForSrc.getSimpleName()),
            getResourceString("NEW_BT_CHOOSE_RSOPT_TITLE"), JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
    if (userChoice == JOptionPane.NO_OPTION) {
        return ASK_TYPE.EnterDataObjs;

    } else if (userChoice == JOptionPane.YES_OPTION) {
        return ASK_TYPE.ChooseRS;
    }
    return ASK_TYPE.Cancel;
}

From source file:com.net2plan.gui.utils.viewEditTopolTables.specificTables.AdvancedJTable_demand.java

private List<JComponent> getExtraOptions(final int row, final Object itemId) {
    List<JComponent> options = new LinkedList<JComponent>();
    final int numRows = model.getRowCount();
    final NetPlan netPlan = callback.getDesign();
    final List<Demand> tableVisibleDemands = getVisibleElementsInTable();

    JMenuItem offeredTrafficToAll = new JMenuItem("Set offered traffic to all");
    offeredTrafficToAll.addActionListener(new ActionListener() {
        @Override//from w ww. j  av  a2s  .c  o  m
        public void actionPerformed(ActionEvent e) {
            double h_d;

            while (true) {
                String str = JOptionPane.showInputDialog(null, "Offered traffic volume",
                        "Set traffic value to all demands in the table", JOptionPane.QUESTION_MESSAGE);
                if (str == null)
                    return;

                try {
                    h_d = Double.parseDouble(str);
                    if (h_d < 0)
                        throw new RuntimeException();

                    break;
                } catch (Throwable ex) {
                    ErrorHandling.showErrorDialog("Please, introduce a non-negative number",
                            "Error setting offered traffic");
                }
            }

            NetPlan netPlan = callback.getDesign();

            try {
                for (Demand d : tableVisibleDemands)
                    d.setOfferedTraffic(h_d);
                callback.getVisualizationState().resetPickedState();
                callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.DEMAND));
                callback.getUndoRedoNavigationManager().addNetPlanChange();
            } catch (Throwable ex) {
                ErrorHandling.showErrorDialog(ex.getMessage(),
                        "Unable to set offered traffic to all demands in the table");
            }
        }
    });
    options.add(offeredTrafficToAll);

    JMenuItem scaleOfferedTrafficToAll = new JMenuItem("Scale offered traffic all demands in the table");
    scaleOfferedTrafficToAll.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            double scalingFactor;

            while (true) {
                String str = JOptionPane.showInputDialog(null,
                        "Scaling factor to multiply to all offered traffics", "Scale offered traffic",
                        JOptionPane.QUESTION_MESSAGE);
                if (str == null)
                    return;

                try {
                    scalingFactor = Double.parseDouble(str);
                    if (scalingFactor < 0)
                        throw new RuntimeException();

                    break;
                } catch (Throwable ex) {
                    ErrorHandling.showErrorDialog("Please, introduce a non-negative number",
                            "Error setting offered traffic");
                }
            }

            try {
                for (Demand d : tableVisibleDemands)
                    d.setOfferedTraffic(d.getOfferedTraffic() * scalingFactor);
                callback.getVisualizationState().resetPickedState();
                callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.DEMAND));
                callback.getUndoRedoNavigationManager().addNetPlanChange();
            } catch (Throwable ex) {
                ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to scale demand offered traffics");
            }
        }
    });
    options.add(scaleOfferedTrafficToAll);

    JMenuItem setServiceTypes = new JMenuItem(
            "Set traversed resource types (to one or all demands in the table)");
    setServiceTypes.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

            NetPlan netPlan = callback.getDesign();
            try {
                Demand d = netPlan.getDemandFromId((Long) itemId);
                String[] headers = StringUtils.arrayOf("Order", "Type");
                Object[][] data = { null, null };
                DefaultTableModel model = new ClassAwareTableModelImpl(data, headers);
                AdvancedJTable table = new AdvancedJTable(model);
                JButton addRow = new JButton("Add new traversed resource type");
                addRow.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Object[] newRow = { table.getRowCount(), "" };
                        ((DefaultTableModel) table.getModel()).addRow(newRow);
                    }
                });
                JButton removeRow = new JButton("Remove selected");
                removeRow.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        ((DefaultTableModel) table.getModel()).removeRow(table.getSelectedRow());
                        for (int t = 0; t < table.getRowCount(); t++)
                            table.getModel().setValueAt(t, t, 0);
                    }
                });
                JButton removeAllRows = new JButton("Remove all");
                removeAllRows.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        while (table.getRowCount() > 0)
                            ((DefaultTableModel) table.getModel()).removeRow(0);
                    }
                });
                List<String> oldTraversedResourceTypes = d.getServiceChainSequenceOfTraversedResourceTypes();
                Object[][] newData = new Object[oldTraversedResourceTypes.size()][headers.length];
                for (int i = 0; i < oldTraversedResourceTypes.size(); i++) {
                    newData[i][0] = i;
                    newData[i][1] = oldTraversedResourceTypes.get(i);
                }
                ((DefaultTableModel) table.getModel()).setDataVector(newData, headers);
                JPanel pane = new JPanel();
                JPanel pane2 = new JPanel();
                pane.setLayout(new BorderLayout());
                pane2.setLayout(new BorderLayout());
                pane.add(new JScrollPane(table), BorderLayout.CENTER);
                pane2.add(addRow, BorderLayout.WEST);
                pane2.add(removeRow, BorderLayout.EAST);
                pane2.add(removeAllRows, BorderLayout.SOUTH);
                pane.add(pane2, BorderLayout.SOUTH);
                final String[] optionsArray = new String[] { "Set to selected demand", "Set to all demands",
                        "Cancel" };
                int result = JOptionPane.showOptionDialog(null, pane, "Set traversed resource types",
                        JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, optionsArray,
                        optionsArray[0]);
                if ((result != 0) && (result != 1))
                    return;
                final boolean setToAllDemands = (result == 1);
                List<String> newTraversedResourcesTypes = new LinkedList<>();
                for (int j = 0; j < table.getRowCount(); j++) {
                    String travResourceType = table.getModel().getValueAt(j, 1).toString();
                    newTraversedResourcesTypes.add(travResourceType);
                }
                if (setToAllDemands) {
                    for (Demand dd : tableVisibleDemands)
                        if (!dd.getRoutes().isEmpty())
                            throw new Net2PlanException(
                                    "It is not possible to set the resource types traversed to demands with routes");
                    for (Demand dd : tableVisibleDemands)
                        dd.setServiceChainSequenceOfTraversedResourceTypes(newTraversedResourcesTypes);
                } else {
                    if (!d.getRoutes().isEmpty())
                        throw new Net2PlanException(
                                "It is not possible to set the resource types traversed to demands with routes");
                    d.setServiceChainSequenceOfTraversedResourceTypes(newTraversedResourcesTypes);
                }
                callback.getVisualizationState().resetPickedState();
                callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.DEMAND));
                callback.getUndoRedoNavigationManager().addNetPlanChange();
            } catch (Throwable ex) {
                ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to set traversed resource types");
            }
        }

    });
    options.add(setServiceTypes);

    if (itemId != null && netPlan.isMultilayer()) {
        final long demandId = (long) itemId;
        if (netPlan.getDemandFromId(demandId).isCoupled()) {
            JMenuItem decoupleDemandItem = new JMenuItem("Decouple demand");
            decoupleDemandItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    netPlan.getDemandFromId(demandId).decouple();
                    model.setValueAt("", row, 3);
                    callback.getVisualizationState().resetPickedState();
                    callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.DEMAND));
                    callback.getUndoRedoNavigationManager().addNetPlanChange();
                }
            });

            options.add(decoupleDemandItem);
        } else {
            JMenuItem createUpperLayerLinkFromDemandItem = new JMenuItem("Create upper layer link from demand");
            createUpperLayerLinkFromDemandItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Collection<Long> layerIds = netPlan.getNetworkLayerIds();
                    final JComboBox layerSelector = new WiderJComboBox();
                    for (long layerId : layerIds) {
                        if (layerId == netPlan.getNetworkLayerDefault().getId())
                            continue;

                        final String layerName = netPlan.getNetworkLayerFromId(layerId).getName();
                        String layerLabel = "Layer " + layerId;
                        if (!layerName.isEmpty())
                            layerLabel += " (" + layerName + ")";

                        layerSelector.addItem(StringLabeller.of(layerId, layerLabel));
                    }

                    layerSelector.setSelectedIndex(0);

                    JPanel pane = new JPanel();
                    pane.add(new JLabel("Select layer: "));
                    pane.add(layerSelector);

                    while (true) {
                        int result = JOptionPane.showConfirmDialog(null, pane,
                                "Please select the upper layer to create the link",
                                JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                        if (result != JOptionPane.OK_OPTION)
                            return;

                        try {
                            long layerId = (long) ((StringLabeller) layerSelector.getSelectedItem())
                                    .getObject();
                            netPlan.getDemandFromId(demandId)
                                    .coupleToNewLinkCreated(netPlan.getNetworkLayerFromId(layerId));
                            callback.getVisualizationState()
                                    .recomputeCanvasTopologyBecauseOfLinkOrNodeAdditionsOrRemovals();
                            callback.updateVisualizationAfterChanges(
                                    Sets.newHashSet(NetworkElementType.DEMAND, NetworkElementType.LINK));
                            callback.getUndoRedoNavigationManager().addNetPlanChange();
                            break;
                        } catch (Throwable ex) {
                            ErrorHandling.showErrorDialog(ex.getMessage(),
                                    "Error creating upper layer link from demand");
                        }
                    }
                }
            });

            options.add(createUpperLayerLinkFromDemandItem);

            JMenuItem coupleDemandToLink = new JMenuItem("Couple demand to upper layer link");
            coupleDemandToLink.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Collection<Long> layerIds = netPlan.getNetworkLayerIds();
                    final JComboBox layerSelector = new WiderJComboBox();
                    final JComboBox linkSelector = new WiderJComboBox();
                    for (long layerId : layerIds) {
                        if (layerId == netPlan.getNetworkLayerDefault().getId())
                            continue;

                        final String layerName = netPlan.getNetworkLayerFromId(layerId).getName();
                        String layerLabel = "Layer " + layerId;
                        if (!layerName.isEmpty())
                            layerLabel += " (" + layerName + ")";

                        layerSelector.addItem(StringLabeller.of(layerId, layerLabel));
                    }

                    layerSelector.addItemListener(new ItemListener() {
                        @Override
                        public void itemStateChanged(ItemEvent e) {
                            if (layerSelector.getSelectedIndex() >= 0) {
                                long selectedLayerId = (Long) ((StringLabeller) layerSelector.getSelectedItem())
                                        .getObject();
                                NetworkLayer selectedLayer = netPlan.getNetworkLayerFromId(selectedLayerId);

                                linkSelector.removeAllItems();
                                Collection<Link> links_thisLayer = netPlan.getLinks(selectedLayer);
                                for (Link link : links_thisLayer) {
                                    if (link.isCoupled())
                                        continue;

                                    String originNodeName = link.getOriginNode().getName();
                                    String destinationNodeName = link.getDestinationNode().getName();

                                    linkSelector.addItem(StringLabeller.unmodifiableOf(link.getId(),
                                            "e" + link.getIndex() + " [n" + link.getOriginNode().getIndex()
                                                    + " (" + originNodeName + ") -> n"
                                                    + link.getDestinationNode().getIndex() + " ("
                                                    + destinationNodeName + ")]"));
                                }
                            }

                            if (linkSelector.getItemCount() == 0) {
                                linkSelector.setEnabled(false);
                            } else {
                                linkSelector.setSelectedIndex(0);
                                linkSelector.setEnabled(true);
                            }
                        }
                    });

                    layerSelector.setSelectedIndex(-1);
                    layerSelector.setSelectedIndex(0);

                    JPanel pane = new JPanel(new MigLayout("", "[][grow]", "[][]"));
                    pane.add(new JLabel("Select layer: "));
                    pane.add(layerSelector, "growx, wrap");
                    pane.add(new JLabel("Select link: "));
                    pane.add(linkSelector, "growx, wrap");

                    while (true) {
                        int result = JOptionPane.showConfirmDialog(null, pane,
                                "Please select the upper layer link", JOptionPane.OK_CANCEL_OPTION,
                                JOptionPane.QUESTION_MESSAGE);
                        if (result != JOptionPane.OK_OPTION)
                            return;

                        try {
                            long layerId = (long) ((StringLabeller) layerSelector.getSelectedItem())
                                    .getObject();
                            long linkId;
                            try {
                                linkId = (long) ((StringLabeller) linkSelector.getSelectedItem()).getObject();
                            } catch (Throwable ex) {
                                throw new RuntimeException("No link was selected");
                            }

                            netPlan.getDemandFromId(demandId)
                                    .coupleToUpperLayerLink(netPlan.getLinkFromId(linkId));
                            callback.getVisualizationState().resetPickedState();
                            callback.updateVisualizationAfterChanges(
                                    Sets.newHashSet(NetworkElementType.DEMAND, NetworkElementType.LINK));
                            callback.getUndoRedoNavigationManager().addNetPlanChange();
                            break;
                        } catch (Throwable ex) {
                            ErrorHandling.showErrorDialog(ex.getMessage(),
                                    "Error coupling upper layer link to demand");
                        }
                    }
                }
            });

            options.add(coupleDemandToLink);
        }

        if (numRows > 1) {
            JMenuItem decoupleAllDemandsItem = null;
            JMenuItem createUpperLayerLinksFromDemandsItem = null;

            final Set<Demand> coupledDemands = tableVisibleDemands.stream().filter(d -> d.isCoupled())
                    .collect(Collectors.toSet());
            if (!coupledDemands.isEmpty()) {
                decoupleAllDemandsItem = new JMenuItem("Decouple all demands");
                decoupleAllDemandsItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        for (Demand d : new LinkedHashSet<Demand>(coupledDemands))
                            d.decouple();
                        int numRows = model.getRowCount();
                        for (int i = 0; i < numRows; i++)
                            model.setValueAt("", i, 3);
                        callback.getVisualizationState().resetPickedState();
                        callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.DEMAND));
                        callback.getUndoRedoNavigationManager().addNetPlanChange();
                    }
                });
            }

            if (coupledDemands.size() < tableVisibleDemands.size()) {
                createUpperLayerLinksFromDemandsItem = new JMenuItem(
                        "Create upper layer links from uncoupled demands");
                createUpperLayerLinksFromDemandsItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Collection<Long> layerIds = netPlan.getNetworkLayerIds();
                        final JComboBox layerSelector = new WiderJComboBox();
                        for (long layerId : layerIds) {
                            if (layerId == netPlan.getNetworkLayerDefault().getId())
                                continue;

                            final String layerName = netPlan.getNetworkLayerFromId(layerId).getName();
                            String layerLabel = "Layer " + layerId;
                            if (!layerName.isEmpty())
                                layerLabel += " (" + layerName + ")";

                            layerSelector.addItem(StringLabeller.of(layerId, layerLabel));
                        }

                        layerSelector.setSelectedIndex(0);

                        JPanel pane = new JPanel();
                        pane.add(new JLabel("Select layer: "));
                        pane.add(layerSelector);

                        while (true) {
                            int result = JOptionPane.showConfirmDialog(null, pane,
                                    "Please select the upper layer to create links",
                                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                            if (result != JOptionPane.OK_OPTION)
                                return;

                            try {
                                long layerId = (long) ((StringLabeller) layerSelector.getSelectedItem())
                                        .getObject();
                                NetworkLayer layer = netPlan.getNetworkLayerFromId(layerId);
                                for (Demand demand : tableVisibleDemands)
                                    if (!demand.isCoupled())
                                        demand.coupleToNewLinkCreated(layer);

                                callback.getVisualizationState()
                                        .recomputeCanvasTopologyBecauseOfLinkOrNodeAdditionsOrRemovals();
                                callback.updateVisualizationAfterChanges(
                                        Sets.newHashSet(NetworkElementType.DEMAND, NetworkElementType.LINK));
                                callback.getUndoRedoNavigationManager().addNetPlanChange();
                                break;
                            } catch (Throwable ex) {
                                ErrorHandling.showErrorDialog(ex.getMessage(),
                                        "Error creating upper layer links");
                            }
                        }
                    }
                });
            }

            if (!options.isEmpty()
                    && (decoupleAllDemandsItem != null || createUpperLayerLinksFromDemandsItem != null)) {
                options.add(new JPopupMenu.Separator());
                if (decoupleAllDemandsItem != null)
                    options.add(decoupleAllDemandsItem);
                if (createUpperLayerLinksFromDemandsItem != null)
                    options.add(createUpperLayerLinksFromDemandsItem);
            }

        }
    }

    return options;
}

From source file:ca.osmcanada.osvuploadr.JPMain.java

private void jbUploadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbUploadActionPerformed
    String path = ca.osmcanada.osvuploadr.JFMain.class.getProtectionDomain().getCodeSource().getLocation()
            .getPath();/*from  ww w.  j  a  v  a2s  .  com*/
    String decodedPath = "";
    try {
        decodedPath = new File(URLDecoder.decode(path, "UTF-8")).getParentFile().getPath();
    } catch (Exception ex) {
        Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, "decodePath", ex);
    }
    File id = new File(decodedPath + "/access_token.txt");
    String accessToken = "";
    System.out.println("id_file exists:" + id.exists());
    if (!id.exists()) {
        try {
            String[] buttons = { new String(r.getString("automatically").getBytes(), "UTF-8"),
                    new String(r.getString("manually").getBytes(), "UTF-8"),
                    new String(r.getString("cancel").getBytes(), "UTF-8") };
            int rc = JOptionPane.showOptionDialog(null,
                    new String(r.getString("login_to_osm").getBytes(), "UTF-8"),
                    new String(r.getString("confirmation").getBytes(), "UTF-8"),
                    JOptionPane.INFORMATION_MESSAGE, 0, null, buttons, buttons[0]);
            String token = "";
            System.out.println("GetOSMUser");
            switch (rc) {
            case 0:
                String usr = "";
                String psw = "";
                JTextField tf = new JTextField();
                JPasswordField pf = new JPasswordField();
                rc = JOptionPane.showConfirmDialog(null, tf,
                        new String(r.getString("email_osm_usr").getBytes(), "UTF-8"),
                        JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
                if (rc == JOptionPane.OK_OPTION) {
                    usr = tf.getText();
                } else {
                    return;
                }

                rc = JOptionPane.showConfirmDialog(null, pf,
                        new String(r.getString("enter_password").getBytes(), "UTF-8"),
                        JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
                if (rc == JOptionPane.OK_OPTION) {
                    psw = new String(pf.getPassword());
                } else {
                    return;
                }
                token = GetOSMUser(usr, psw);
                break;
            case 1:
                token = GetOSMUser();
                break;
            case 2:
                return;

            }
            Path targetPath = Paths.get("./access_token.txt");
            byte[] bytes = token.split("\\|")[0].getBytes(StandardCharsets.UTF_8);
            Files.write(targetPath, bytes, StandardOpenOption.CREATE);
            accessToken = token.split("\\|")[0];
            String accessSecret = token.split("\\|")[1];
            SendAuthTokens(accessToken, accessSecret);
        } catch (Exception ex) {
            Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, "GetOSMUser", ex);
        }
    } else {
        try {
            List<String> token = Files.readAllLines(Paths.get(id.getPath()));
            if (token.size() > 0) {
                accessToken = token.get(0); //read first line
            }
        } catch (Exception ex) {
            Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, "readAllLines", ex);
        }
    }
    System.out.println("Access Token obtained from file or OSM:" + accessToken);

    //Start processing list
    for (String item : listDir.getItems()) {
        System.out.println("Processing folder:" + item);
        Process(item, accessToken);
    }
    //um = new UploadManager(listDir.getItems());
    //um.start();

}