Example usage for javax.swing JOptionPane getValue

List of usage examples for javax.swing JOptionPane getValue

Introduction

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

Prototype

public Object getValue() 

Source Link

Document

Returns the value the user has selected.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    JOptionPane pane = new JOptionPane("your message", JOptionPane.ERROR_MESSAGE, JOptionPane.OK_OPTION);
    JDialog d = pane.createDialog(null, "title");
    d.pack();//from w  ww .java 2 s.  c  o  m
    d.setModal(false);
    d.setVisible(true);
    while (pane.getValue() == JOptionPane.UNINITIALIZED_VALUE) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException ie) {
        }
    }
    System.exit(0);
}

From source file:AskingQuestionDialog.java

public static void main(String argv[]) {
    JOptionPane pane = new JOptionPane("To be or not to be ?\nThat is the question.");
    Object[] options = new String[] { "To be", "Not to be" };
    pane.setOptions(options);//from  ww w.  j a v  a  2 s  .c om
    JDialog dialog = pane.createDialog(new JFrame(), "Dilaog");
    dialog.show();
    Object obj = pane.getValue();
    int result = -1;
    for (int k = 0; k < options.length; k++)
        if (options[k].equals(obj))
            result = k;
    System.out.println("User's choice: " + result);
}

From source file:JOptionPaneDemonstrationLocalized.java

public static void main(String[] argv) {

        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        Font unicodeFont = new Font("LucidaSans", Font.PLAIN, 12);

        ResourceBundle bundle = ResourceBundle.getBundle("JOptionPaneResources", Locale.getDefault());

        String[] textMessages = new String[3];
        textMessages[0] = bundle.getString("Yes");
        textMessages[1] = bundle.getString("No");
        textMessages[2] = bundle.getString("Cancel");

        JOptionPane jop = new JOptionPane(bundle.getString("MessageText"), JOptionPane.ERROR_MESSAGE,
                JOptionPane.YES_NO_CANCEL_OPTION, null, textMessages);
        JDialog jopDialog = jop.createDialog(null, bundle.getString("TitleText"));
        jop.setFont(unicodeFont);//from   w ww.  j  a  v  a 2  s . c om
        jopDialog.setVisible(true);
        Object userSelection = jop.getValue();
    }

From source file:Main.java

public static void main(String[] args) {
    String[] options = { "Button 1", "Button 2", "Button 3" };

    JOptionPane myOptionPane = new JOptionPane("Heres a test message", JOptionPane.QUESTION_MESSAGE,
            JOptionPane.YES_NO_OPTION, null, options, options[2]);
    JDialog myDialog = myOptionPane.createDialog(null, "My Test");
    myDialog.setModal(true);//from  ww  w . j  a va  2s . c  o m

    inactivateOption(myDialog, options[1]);

    myDialog.setVisible(true);
    Object result = myOptionPane.getValue();
    System.out.println("result: " + result);

}

From source file:GettingJOptionPaneSelectionDemo.java

public static int getSelection(JOptionPane optionPane) {
    int returnValue = JOptionPane.CLOSED_OPTION;

    Object selectedValue = optionPane.getValue();
    if (selectedValue != null) {
        Object options[] = optionPane.getOptions();
        if (options == null) {
            if (selectedValue instanceof Integer) {
                returnValue = ((Integer) selectedValue).intValue();
            }//from w w  w  . j  a  v a2  s.  c o m
        } else {
            for (int i = 0, n = options.length; i < n; i++) {
                if (options[i].equals(selectedValue)) {
                    returnValue = i;
                    break; // out of for loop
                }
            }
        }
    }
    return returnValue;
}

From source file:Main.java

/** Show a confirmation message box with line wrapped message.
 *
 * 'optionType' is one of the JOptionPane.XXX_OPTION combination
 * constants, and the return value is one of the single-value
 * constants. *//* w w w  . j av a2s .  c o m*/
public static int confirmationBox(Component parent, String message, String title, int optionType) {
    JOptionPane pane = makeWordWrapJOptionPane();
    pane.setMessage(message);
    pane.setMessageType(JOptionPane.QUESTION_MESSAGE);
    pane.setOptionType(optionType);

    JDialog dialog = pane.createDialog(parent, title);
    dialog.setVisible(true);

    Object result = pane.getValue();
    if (result == null || !(result instanceof Integer)) {
        return JOptionPane.CLOSED_OPTION;
    } else {
        return ((Integer) result).intValue();
    }
}

From source file:MessagePopup.java

public static int getSelection(JOptionPane optionPane) {
    // Default return value, signals nothing selected
    int returnValue = JOptionPane.CLOSED_OPTION;

    // Get selected Value
    Object selectedValue = optionPane.getValue();
    System.out.println(selectedValue);

    // If none, then nothing selected
    if (selectedValue != null) {
        Object options[] = optionPane.getOptions();
        if (options == null) {
            // default buttons, no array specified
            if (selectedValue instanceof Integer) {
                returnValue = ((Integer) selectedValue).intValue();
            }//from   w  w  w.  ja v  a  2  s.com
        } else {
            // Array of option buttons specified
            for (int i = 0, n = options.length; i < n; i++) {
                if (options[i].equals(selectedValue)) {
                    returnValue = i;
                    break; // out of for loop
                }
            }
        }
    }
    return returnValue;
}

From source file:eu.delving.sip.base.VisualFeedback.java

public static boolean askOption(JDesktopPane desktop, Object message, String title, int optionType,
        int messageType) {
    JOptionPane pane = new JOptionPane(message, messageType, optionType, null, null, null);
    pane.putClientProperty(new Object(), Boolean.TRUE);
    JDialog frame = pane.createDialog(desktop, title);
    pane.selectInitialValue();/*from   w w w. j av  a 2  s  .c  o m*/
    frame.setVisible(true);
    acquireFocus();
    Object selectedValue = pane.getValue();
    return selectedValue != null && selectedValue instanceof Integer && (Integer) selectedValue == YES_OPTION;
}

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

/** Helper method for constructing an always-on-top modal dialog. */
public static Object show(String title, int type, Object message, Object[] options, Object initialOption) {
    if (options == null) {
        options = new Object[] { "Ok" };
        initialOption = "Ok";
    }/*from   w  ww  . ja v a 2s .co m*/
    JOptionPane p = new JOptionPane(message, type, JOptionPane.DEFAULT_OPTION, null, options, initialOption);
    p.setInitialValue(initialOption);
    JDialog d = p.createDialog(null, title);
    p.selectInitialValue();
    d.setAlwaysOnTop(true);
    d.setVisible(true);
    d.dispose();
    return p.getValue();
}

From source file:com.t3.macro.api.functions.input.InputFunctions.java

/**
 * <pre>/*ww w.  j  a  va 2 s. c  o  m*/
 * <span style="font-family:sans-serif;">The input() function prompts the user to input several variable values at once.
 * 
 * Each of the string parameters has the following format:
 *     "varname|value|prompt|inputType|options"
 * 
 * Only the first section is required.
 *     varname   - the variable name to be assigned
 *     value     - sets the initial contents of the input field
 *     prompt    - UI text shown for the variable
 *     inputType - specifies the type of input field
 *     options   - a string of the form "opt1=val1; opt2=val2; ..."
 * 
 * The inputType field can be any of the following (defaults to TEXT):
 *     TEXT  - A text field.
 *             "value" sets the initial contents.
 *             The return value is the string in the text field.
 *             Option: WIDTH=nnn sets the width of the text field (default 16).
 *     LIST  - An uneditable combo box.
 *             "value" populates the list, and has the form "item1,item2,item3..." (trailing empty strings are dropped)
 *             The return value is the numeric index of the selected item.
 *             Option: SELECT=nnn sets the initial selection (default 0).
 *             Option: VALUE=STRING returns the string contents of the selected item (default NUMBER).
 *             Option: TEXT=FALSE suppresses the text of the list item (default TRUE).
 *             Option: ICON=TRUE causes icon asset URLs to be extracted from the "value" and displayed (default FALSE).
 *             Option: ICONSIZE=nnn sets the size of the icons (default 50).
 *     CHECK - A checkbox.
 *             "value" sets the initial state of the box (anything but "" or "0" checks the box)
 *             The return value is 0 or 1.
 *             No options.
 *     RADIO - A group of radio buttons.
 *             "value" is a list "name1, name2, name3, ..." which sets the labels of the buttons.
 *             The return value is the index of the selected item.
 *             Option: SELECT=nnn sets the initial selection (default 0).
 *             Option: ORIENT=H causes the radio buttons to be laid out on one line (default V).
 *             Option: VALUE=STRING causes the return value to be the string of the selected item (default NUMBER).
 *     LABEL - A label.
 *             The "varname" is ignored and no value is assigned to it.
 *             Option: TEXT=FALSE, ICON=TRUE, ICONSIZE=nnn, as in the LIST type.
 *     PROPS - A sub-panel with multiple text boxes.
 *             "value" contains a StrProp of the form "key1=val1; key2=val2; ..."
 *             One text box is created for each key, populated with the matching value.
 *             Option: SETVARS=SUFFIXED causes variable assignment to each key name, with appended "_" (default NONE).
 *             Option: SETVARS=UNSUFFIXED causes variable assignment to each key name.
 *     TAB   - A tabbed dialog tab is created.  Subsequent variables are contained in the tab.
 *             Option: SELECT=TRUE causes this tab to be shown at start (default SELECT=FALSE).
 * 
 *  All inputTypes except TAB accept the option SPAN=TRUE, which causes the prompt to be hidden and the input
 *  control to span both columns of the dialog layout (default FALSE).
 * </span>
 * </pre>
 * @param parameters a list of strings containing information as described above
 * @return a HashMap with the returned values or null if the user clicked on cancel
 * @author knizia.fan
 * @throws MacroException 
 */
public static Map<String, String> input(TokenView token, String... parameters) throws MacroException {
    // Extract the list of specifier strings from the parameters
    // "name | value | prompt | inputType | options"
    List<String> varStrings = new ArrayList<String>();
    for (Object param : parameters) {
        String paramStr = (String) param;
        if (StringUtils.isEmpty(paramStr)) {
            continue;
        }
        // Multiple vars can be packed into a string, separated by "##"
        for (String varString : StringUtils.splitByWholeSeparator(paramStr, "##")) {
            if (StringUtils.isEmpty(paramStr)) {
                continue;
            }
            varStrings.add(varString);
        }
    }

    // Create VarSpec objects from each variable's specifier string
    List<VarSpec> varSpecs = new ArrayList<VarSpec>();
    for (String specifier : varStrings) {
        VarSpec vs;
        try {
            vs = new VarSpec(specifier);
        } catch (VarSpec.SpecifierException se) {
            throw new MacroException(se);
        } catch (InputType.OptionException oe) {
            throw new MacroException(I18N.getText("macro.function.input.invalidOptionType", oe.key, oe.value,
                    oe.type, specifier));
        }
        varSpecs.add(vs);
    }

    // Check if any variables were defined
    if (varSpecs.isEmpty())
        return Collections.emptyMap(); // No work to do, so treat it as a successful invocation.

    // UI step 1 - First, see if a token is given

    String dialogTitle = "Input Values";
    if (token != null) {
        String name = token.getName(), gm_name = token.getGMName();
        boolean isGM = TabletopTool.getPlayer().isGM();
        String extra = "";

        if (isGM && gm_name != null && gm_name.compareTo("") != 0)
            extra = " for " + gm_name;
        else if (name != null && name.compareTo("") != 0)
            extra = " for " + name;

        dialogTitle = dialogTitle + extra;
    }

    // UI step 2 - build the panel with the input fields
    InputPanel ip = new InputPanel(varSpecs);

    // Calculate the height
    // TODO: remove this workaround
    int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
    int maxHeight = screenHeight * 3 / 4;
    Dimension ipPreferredDim = ip.getPreferredSize();
    if (maxHeight < ipPreferredDim.height) {
        ip.modifyMaxHeightBy(maxHeight - ipPreferredDim.height);
    }

    // UI step 3 - show the dialog
    JOptionPane jop = new JOptionPane(ip, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
    JDialog dlg = jop.createDialog(TabletopTool.getFrame(), dialogTitle);

    // Set up callbacks needed for desired runtime behavior
    dlg.addComponentListener(new FixupComponentAdapter(ip));

    dlg.setVisible(true);
    int dlgResult = JOptionPane.CLOSED_OPTION;
    try {
        dlgResult = (Integer) jop.getValue();
    } catch (NullPointerException npe) {
    }
    dlg.dispose();

    if (dlgResult == JOptionPane.CANCEL_OPTION || dlgResult == JOptionPane.CLOSED_OPTION)
        return null;

    HashMap<String, String> results = new HashMap<String, String>();

    // Finally, assign values from the dialog box to the variables
    for (ColumnPanel cp : ip.columnPanels) {
        List<VarSpec> panelVars = cp.varSpecs;
        List<JComponent> panelControls = cp.inputFields;
        int numPanelVars = panelVars.size();
        StringBuilder allAssignments = new StringBuilder(); // holds all values assigned in this tab

        for (int varCount = 0; varCount < numPanelVars; varCount++) {
            VarSpec vs = panelVars.get(varCount);
            JComponent comp = panelControls.get(varCount);
            String newValue = null;
            switch (vs.inputType) {
            case TEXT: {
                newValue = ((JTextField) comp).getText();
                break;
            }
            case LIST: {
                Integer index = ((JComboBox) comp).getSelectedIndex();
                if (vs.optionValues.optionEquals("VALUE", "STRING")) {
                    newValue = vs.valueList.get(index);
                } else { // default is "NUMBER"
                    newValue = index.toString();
                }
                break;
            }
            case CHECK: {
                Integer value = ((JCheckBox) comp).isSelected() ? 1 : 0;
                newValue = value.toString();
                break;
            }
            case RADIO: {
                // This code assumes that the Box container returns components
                // in the same order that they were added.
                Component[] comps = ((Box) comp).getComponents();
                int componentCount = 0;
                Integer index = 0;
                for (Component c : comps) {
                    if (c instanceof JRadioButton) {
                        JRadioButton radio = (JRadioButton) c;
                        if (radio.isSelected())
                            index = componentCount;
                    }
                    componentCount++;
                }
                if (vs.optionValues.optionEquals("VALUE", "STRING")) {
                    newValue = vs.valueList.get(index);
                } else { // default is "NUMBER"
                    newValue = index.toString();
                }
                break;
            }
            case LABEL: {
                newValue = null;
                // The variable name is ignored and not set.
                break;
            }
            case PROPS: {
                // Read out and assign all the subvariables.
                // The overall return value is a property string (as in StrPropFunctions.java) with all the new settings.
                Component[] comps = ((JPanel) comp).getComponents();
                StringBuilder sb = new StringBuilder();
                int setVars = 0; // "NONE", no assignments made
                if (vs.optionValues.optionEquals("SETVARS", "SUFFIXED"))
                    setVars = 1;
                if (vs.optionValues.optionEquals("SETVARS", "UNSUFFIXED"))
                    setVars = 2;
                if (vs.optionValues.optionEquals("SETVARS", "TRUE"))
                    setVars = 2; // for backward compatibility
                for (int compCount = 0; compCount < comps.length; compCount += 2) {
                    String key = ((JLabel) comps[compCount]).getText().split("\\:")[0]; // strip trailing colon
                    String value = ((JTextField) comps[compCount + 1]).getText();
                    sb.append(key);
                    sb.append("=");
                    sb.append(value);
                    sb.append(" ; ");
                    switch (setVars) {
                    case 0:
                        // Do nothing
                        break;
                    case 1:
                        results.put(key + "_", value);
                        break;
                    case 2:
                        results.put(key, value);
                        break;
                    }
                }
                newValue = sb.toString();
                break;
            }
            default:
                // should never happen
                newValue = null;
                break;
            }
            // Set the variable to the value we got from the dialog box.
            if (newValue != null) {
                results.put(vs.name, newValue.trim());
                allAssignments.append(vs.name + "=" + newValue.trim() + " ## ");
            }
        }
        if (cp.tabVarSpec != null) {
            results.put(cp.tabVarSpec.name, allAssignments.toString());
        }
    }

    return results; // success

    // for debugging:
    //return debugOutput(varSpecs);
}