Example usage for javax.swing JOptionPane CANCEL_OPTION

List of usage examples for javax.swing JOptionPane CANCEL_OPTION

Introduction

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

Prototype

int CANCEL_OPTION

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

Click Source Link

Document

Return value from class method if CANCEL is chosen.

Usage

From source file:net.sf.housekeeper.HousekeeperLifecycleAdvisor.java

/**
 * Ask if user wants to save before exiting.
 *//*from w ww.j  a  v  a 2 s  .c  o m*/
public boolean onPreWindowClose(ApplicationWindow window) {
    boolean exit = true;

    final ActionCommand saveCommand = window.getCommandManager().getActionCommand("saveCommand");

    // Only show dialog for saving before exiting if any data has been
    // changed
    if (saveCommand.isEnabled()) {
        final String question = getApplicationServices().getMessages()
                .getMessage("gui.mainFrame.saveModificationsQuestion");
        final int option = JOptionPane.showConfirmDialog(window.getControl(), question);

        // If user choses yes try to save. If that fails do not exit.
        if (option == JOptionPane.YES_OPTION) {
            saveCommand.execute();

        } else if (option == JOptionPane.CANCEL_OPTION) {
            exit = false;
        }
    }
    return exit;
}

From source file:net.pms.newgui.Wizard.java

public static void run(final PmsConfiguration configuration) {
    // Total number of questions
    int numberOfQuestions = Platform.isMac() ? 4 : 5;

    // The current question number
    int currentQuestionNumber = 1;

    String status = new StringBuilder().append(Messages.getString("Wizard.2")).append(" %d ")
            .append(Messages.getString("Wizard.4")).append(" ").append(numberOfQuestions).toString();

    Object[] okOptions = { Messages.getString("Dialog.OK") };

    Object[] yesNoOptions = { Messages.getString("Dialog.YES"), Messages.getString("Dialog.NO") };

    Object[] networkTypeOptions = { Messages.getString("Wizard.8"), Messages.getString("Wizard.9"),
            Messages.getString("Wizard.10") };

    if (!Platform.isMac()) {
        // Ask if they want UMS to start minimized
        int whetherToStartMinimized = JOptionPane.showOptionDialog(null, Messages.getString("Wizard.3"),
                String.format(status, currentQuestionNumber++), JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE, null, yesNoOptions, yesNoOptions[1]);

        if (whetherToStartMinimized == JOptionPane.YES_OPTION) {
            configuration.setMinimized(true);
        } else if (whetherToStartMinimized == JOptionPane.NO_OPTION) {
            configuration.setMinimized(false);
        }//  w  w  w  .  j a  v a 2s.co  m
    }

    // Ask if their network is wired, etc.
    int networkType = JOptionPane.showOptionDialog(null, Messages.getString("Wizard.7"),
            String.format(status, currentQuestionNumber++), JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, networkTypeOptions, networkTypeOptions[1]);

    switch (networkType) {
    case JOptionPane.YES_OPTION:
        // Wired (Gigabit)
        configuration.setMaximumBitrate("0");
        configuration.setMPEG2MainSettings("Automatic (Wired)");
        configuration.setx264ConstantRateFactor("Automatic (Wired)");
        break;
    case JOptionPane.NO_OPTION:
        // Wired (100 Megabit)
        configuration.setMaximumBitrate("90");
        configuration.setMPEG2MainSettings("Automatic (Wired)");
        configuration.setx264ConstantRateFactor("Automatic (Wired)");
        break;
    case JOptionPane.CANCEL_OPTION:
        // Wireless
        configuration.setMaximumBitrate("30");
        configuration.setMPEG2MainSettings("Automatic (Wireless)");
        configuration.setx264ConstantRateFactor("Automatic (Wireless)");
        break;
    default:
        break;
    }

    // Ask if they want to hide advanced options
    int whetherToHideAdvancedOptions = JOptionPane.showOptionDialog(null, Messages.getString("Wizard.11"),
            String.format(status, currentQuestionNumber++), JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, yesNoOptions, yesNoOptions[0]);

    if (whetherToHideAdvancedOptions == JOptionPane.YES_OPTION) {
        configuration.setHideAdvancedOptions(true);
    } else if (whetherToHideAdvancedOptions == JOptionPane.NO_OPTION) {
        configuration.setHideAdvancedOptions(false);
    }

    // Ask if they want to scan shared folders
    int whetherToScanSharedFolders = JOptionPane.showOptionDialog(null,
            Messages.getString("Wizard.IsStartupScan"), String.format(status, currentQuestionNumber++),
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, yesNoOptions, yesNoOptions[0]);

    if (whetherToScanSharedFolders == JOptionPane.YES_OPTION) {
        configuration.setScanSharedFoldersOnStartup(true);
    } else if (whetherToScanSharedFolders == JOptionPane.NO_OPTION) {
        configuration.setScanSharedFoldersOnStartup(false);
    }

    // Ask to set at least one shared folder
    JOptionPane.showOptionDialog(null, Messages.getString("Wizard.12"),
            String.format(status, currentQuestionNumber++), JOptionPane.OK_OPTION,
            JOptionPane.INFORMATION_MESSAGE, null, okOptions, okOptions[0]);

    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                JFileChooser chooser;
                try {
                    chooser = new JFileChooser();
                } catch (Exception ee) {
                    chooser = new JFileChooser(new RestrictedFileSystemView());
                }

                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                chooser.setDialogTitle(Messages.getString("Wizard.12"));
                chooser.setMultiSelectionEnabled(false);
                if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
                    configuration.setOnlySharedDirectory(chooser.getSelectedFile().getAbsolutePath());
                } else {
                    // If the user cancels this option, the default directories will be used.
                }
            }
        });
    } catch (InterruptedException | InvocationTargetException e) {
        LOGGER.error("Error when saving folders: ", e);
    }

    // The wizard finished, do not ask them again
    configuration.setRunWizard(false);

    // Save all changes
    try {
        configuration.save();
    } catch (ConfigurationException e) {
        LOGGER.error("Error when saving changed configuration: ", e);
    }
}

From source file:net.menthor.editor.v2.util.Util.java

public static JFileChooser createChooser(String lastPath, final boolean checkOverrideFile) {
    return new JFileChooser(lastPath) {
        private static final long serialVersionUID = 1L;

        @Override/*from   w w  w .j  a  v a 2  s  .c o m*/
        public void approveSelection() {
            File f = getSelectedFile();
            if (f.exists() && checkOverrideFile) {
                int result = JOptionPane.showConfirmDialog(this,
                        "\"" + f.getName() + "\" already exists. Do you want to overwrite it?", "Existing file",
                        JOptionPane.YES_NO_CANCEL_OPTION);
                switch (result) {
                case JOptionPane.YES_OPTION:
                    super.approveSelection();
                    return;
                case JOptionPane.NO_OPTION:
                    return;
                case JOptionPane.CLOSED_OPTION:
                    return;
                case JOptionPane.CANCEL_OPTION:
                    cancelSelection();
                    return;
                }
            }
            super.approveSelection();
        }
    };
}

From source file:eu.dety.burp.joseph.utilities.Converter.java

/**
 * Get RSA PublicKey by PublicKey HashMap input. Create a dialog popup with a combobox to choose the correct JWK to use.
 * /*from   w w w. j  a  v  a2 s.c o  m*/
 * @param publicKeys
 *            HashMap containing a PublicKey and related describing string
 * @throws AttackPreparationFailedException
 * @return Selected {@link PublicKey}
 */
@SuppressWarnings("unchecked")
public static PublicKey getRsaPublicKeyByJwkSelectionPanel(HashMap<String, PublicKey> publicKeys)
        throws AttackPreparationFailedException {
    // TODO: Move to other class?
    JPanel selectionPanel = new JPanel();
    selectionPanel.setLayout(new java.awt.GridBagLayout());
    GridBagConstraints constraints = new GridBagConstraints();
    constraints.fill = GridBagConstraints.HORIZONTAL;

    constraints.gridy = 0;
    selectionPanel.add(new JLabel("Multiple JWKs found. Please choose one:"), constraints);

    JComboBox jwkSetKeySelection = new JComboBox<>();
    DefaultComboBoxModel<String> jwkSetKeySelectionModel = new DefaultComboBoxModel<>();

    for (Map.Entry<String, PublicKey> publicKey : publicKeys.entrySet()) {
        jwkSetKeySelectionModel.addElement(publicKey.getKey());
    }

    jwkSetKeySelection.setModel(jwkSetKeySelectionModel);

    constraints.gridy = 1;
    selectionPanel.add(jwkSetKeySelection, constraints);

    int resultButton = JOptionPane.showConfirmDialog(null, selectionPanel, "Select JWK",
            JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);

    if (resultButton == JOptionPane.CANCEL_OPTION) {
        throw new AttackPreparationFailedException("No JWK from JWK Set selected!");
    }

    loggerInstance.log(Converter.class, "Key selected: " + jwkSetKeySelection.getSelectedIndex(),
            Logger.LogLevel.DEBUG);
    return publicKeys.get(jwkSetKeySelection.getSelectedItem());
}

From source file:com.sun.jersey.client.apache.config.DefaultCredentialsProvider.java

public Credentials getCredentials(AuthScheme scheme, String host, int port, boolean proxy)
        throws CredentialsNotAvailableException {
    if (scheme == null) {
        return null;
    }/*from  w w  w  .ja  va2  s  . c  o  m*/

    try {
        JTextField userField = new JTextField();
        JPasswordField passwordField = new JPasswordField();
        int response;

        if (scheme instanceof NTLMScheme) {
            JTextField domainField = new JTextField();
            Object[] msg = { host + ":" + port + " requires Windows authentication", "Domain", domainField,
                    "User Name", userField, "Password", passwordField };
            response = JOptionPane.showConfirmDialog(null, msg, "Authenticate", JOptionPane.OK_CANCEL_OPTION);

            if ((response == JOptionPane.CANCEL_OPTION) || (response == JOptionPane.CLOSED_OPTION)) {
                throw new CredentialsNotAvailableException("User cancled windows authentication.");
            }

            return new NTCredentials(userField.getText(), new String(passwordField.getPassword()), host,
                    domainField.getText());

        } else if (scheme instanceof RFC2617Scheme) {
            Object[] msg = {
                    host + ":" + port + " requires authentication with the realm '" + scheme.getRealm() + "'",
                    "User Name", userField, "Password", passwordField };

            response = JOptionPane.showConfirmDialog(null, msg, "Authenticate", JOptionPane.OK_CANCEL_OPTION);

            if ((response == JOptionPane.CANCEL_OPTION) || (response == JOptionPane.CLOSED_OPTION)) {
                throw new CredentialsNotAvailableException("User cancled windows authentication.");
            }

            return new UsernamePasswordCredentials(userField.getText(),
                    new String(passwordField.getPassword()));

        } else {

            throw new CredentialsNotAvailableException(
                    "Unsupported authentication scheme: " + scheme.getSchemeName());

        }
    } catch (IOException ioe) {

        throw new CredentialsNotAvailableException(ioe.getMessage(), ioe);

    }
}

From source file:eu.ggnet.dwoss.redtape.action.StateTransitionAction.java

@Override
public void actionPerformed(ActionEvent e) {
    //TODO: All the extra checks for hints don't feel like the optimum

    //Invoice//from www  . j a  v  a 2s. c om
    if (((RedTapeStateTransition) transition).getHints()
            .contains(RedTapeStateTransition.Hint.CREATES_INVOICE)) {
        int confirmInvoice = JOptionPane.showOptionDialog(parent,
                "Eine Rechnung wird unwiederruflich erstellt. Mchten Sie fortfahren?", "Rechnungserstellung",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);
        if (confirmInvoice == JOptionPane.CANCEL_OPTION)
            return;
    }

    //Cancel
    if (((RedTapeStateTransition) transition).equals(RedTapeStateTransitions.CANCEL)) {
        int confirmInvoice = JOptionPane.showOptionDialog(parent,
                "Der Vorgang wird storniert.\nMchten Sie fortfahren?", "Abbrechen des Vorganges",
                JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);
        if (confirmInvoice == JOptionPane.NO_OPTION)
            return;
    }

    if (((RedTapeStateTransition) transition).getHints()
            .contains(RedTapeStateTransition.Hint.ADDS_SETTLEMENT)) {
        SettlementViewCask view = new SettlementViewCask();
        OkCancelDialog<SettlementViewCask> dialog = new OkCancelDialog<>(parent, "Zahlung hinterlegen", view);
        dialog.setVisible(true);
        if (dialog.getCloseType() == CloseType.OK) {
            for (Document.Settlement settlement : view.getSettlements()) {
                cdoc.getDocument().add(settlement);
            }
        } else {
            return;
        }
    }
    if (((RedTapeStateTransition) transition).getHints()
            .contains(RedTapeStateTransition.Hint.UNIT_LEAVES_STOCK)) {
        for (Position p : cdoc.getDocument().getPositions(PositionType.PRODUCT_BATCH).values()) {
            //TODO not the best but fastest solution for now, this must be changed later
            if (StringUtils.isBlank(p.getRefurbishedId())) {
                if (JOptionPane.showConfirmDialog(parent,
                        "Der Vorgang enthlt Neuware, wurden alle Seriennummern erfasst?",
                        "Bitte verifizieren", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.CANCEL_OPTION)
                    return;
            }
        }
    }
    Dossier d = lookup(RedTapeWorker.class).stateChange(cdoc, transition, lookup(Guardian.class).getUsername())
            .getDossier();
    controller.reloadSelectionOnStateChange(d);
}

From source file:com.igormaznitsa.zxpspritecorrector.files.AbstractFilePlugin.java

protected boolean saveDataToFile(final File file, final byte[] data) throws IOException {
    if (file.isFile()) {
        switch (JOptionPane.showConfirmDialog(this.mainFrame,
                "Overwrite file '" + file.getAbsolutePath() + "'?", "Overwrite file",
                JOptionPane.YES_NO_CANCEL_OPTION)) {
        case JOptionPane.NO_OPTION:
            return true;
        case JOptionPane.CANCEL_OPTION:
            return false;
        }/*from w w  w .j ava 2  s  .  c o  m*/
    }
    FileUtils.writeByteArrayToFile(file, data);
    return true;
}

From source file:OptPaneComparison.java

protected String getOptionPaneValue() {

    // Get the result . . .
    Object o = optPane.getInputValue();
    String s = "<Unknown>";
    if (o != null)
        s = (String) o;//from   w w w.j  a va  2s . c o m

    Object val = optPane.getValue(); // which button?

    // Check for cancel button or closed option
    if (val != null) {
        if (val instanceof Integer) {
            int intVal = ((Integer) val).intValue();
            if ((intVal == JOptionPane.CANCEL_OPTION) || (intVal == JOptionPane.CLOSED_OPTION))
                s = "<Cancel>";
        }
    }

    // A little trick to clean the text field. It is only updated if
    // the initial value gets changed. To do this, we'll set it to a
    // dummy value ("X") and then clear it.
    optPane.setValue("");
    optPane.setInitialValue("X");
    optPane.setInitialValue("");

    return s;
}

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

private void initComponents(Channel channel) {
    label1 = new JLabel("   The following code template libraries are linked to this channel:");
    label1.setIcon(UIManager.getIcon("OptionPane.questionIcon"));

    librariesTextPane = new JTextPane();
    librariesTextPane.setContentType("text/html");
    HTMLEditorKit editorKit = new HTMLEditorKit();
    StyleSheet styleSheet = editorKit.getStyleSheet();
    styleSheet.addRule(".export-channel-libraries-dialog {font-family:\"Tahoma\";font-size:11;text-align:top}");
    librariesTextPane.setEditorKit(editorKit);
    librariesTextPane.setEditable(false);
    librariesTextPane.setBackground(getBackground());
    librariesTextPane.setBorder(null);/*ww  w  .jav a2 s  .  c  om*/

    StringBuilder librariesText = new StringBuilder("<html><ul class=\"export-channel-libraries-dialog\">");
    for (CodeTemplateLibrary library : PlatformUI.MIRTH_FRAME.codeTemplatePanel.getCachedCodeTemplateLibraries()
            .values()) {
        if (library.getEnabledChannelIds().contains(channel.getId()) || (library.isIncludeNewChannels()
                && !library.getDisabledChannelIds().contains(channel.getId()))) {
            librariesText.append("<li>").append(StringEscapeUtils.escapeHtml4(library.getName()))
                    .append("</li>");
        }
    }
    librariesText.append("</ul></html>");
    librariesTextPane.setText(librariesText.toString());
    librariesTextPane.setCaretPosition(0);

    librariesScrollPane = new JScrollPane(librariesTextPane);

    label2 = new JLabel("Do you wish to include these libraries in the channel export?");

    alwaysChooseCheckBox = new JCheckBox(
            "Always choose this option by default in the future (may be changed in the Administrator settings)");

    yesButton = new JButton("Yes");
    yesButton.setMnemonic('Y');
    yesButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            result = JOptionPane.YES_OPTION;
            if (alwaysChooseCheckBox.isSelected()) {
                Preferences.userNodeForPackage(Mirth.class).putBoolean("exportChannelCodeTemplateLibraries",
                        true);
            }
            dispose();
        }
    });

    noButton = new JButton("No");
    noButton.setMnemonic('N');
    noButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            result = JOptionPane.NO_OPTION;
            if (alwaysChooseCheckBox.isSelected()) {
                Preferences.userNodeForPackage(Mirth.class).putBoolean("exportChannelCodeTemplateLibraries",
                        false);
            }
            dispose();
        }
    });

    cancelButton = new JButton("Cancel");
    cancelButton.setMnemonic('C');
    cancelButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            result = JOptionPane.CANCEL_OPTION;
            dispose();
        }
    });
}

From source file:com.projity.dialog.TransformParameterDialog.java

public void execute(Object obj) {
    labels.clear();/*  w  w  w.ja  v a 2s  .  co  m*/
    valueComponents.clear();
    transform = (CommonTransform) obj;
    TransformParameter param;
    for (Iterator i = transform.getParameters().iterator(); i.hasNext();) {
        param = (TransformParameter) i.next();
        labels.add(/*new JLabel(*/Messages.getString(param.getId())/*)*/);
        ExtDateField dateChooser = new ExtDateField(); //ComponentFactory.createDateField(); 

        Date date = param.getValue() == null ? new Date(DateTime.midnightToday())
                : new Date((Long) param.getValue());
        dateChooser.setValue(date);
        valueComponents.add(dateChooser);
    }
    clearComponents();

    pack();
    bind(true);
    setLocationRelativeTo(getParent());//to center on screen
    setVisible(true);
    if (getDialogResult() != JOptionPane.CANCEL_OPTION) {
        bind(false);
    }
}