Example usage for javax.swing JDialog addComponentListener

List of usage examples for javax.swing JDialog addComponentListener

Introduction

In this page you can find the example usage for javax.swing JDialog addComponentListener.

Prototype

public synchronized void addComponentListener(ComponentListener l) 

Source Link

Document

Adds the specified component listener to receive component events from this component.

Usage

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

/**
 * <pre>//from   w  w w  .ja  v  a 2s.  c om
 * <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);
}

From source file:com.gs.obevo.util.inputreader.DialogInputReader.java

@Override
public String readPassword(String promptMessage) {
    final JPasswordField jpf = new JPasswordField();
    JOptionPane jop = new JOptionPane(jpf, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
    JDialog dialog = jop.createDialog(promptMessage);
    dialog.addComponentListener(new ComponentAdapter() {
        @Override/*  w  w w.  jav  a 2 s. c  om*/
        public void componentShown(ComponentEvent e) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    jpf.requestFocusInWindow();
                }
            });
        }
    });
    dialog.setVisible(true);
    int result = (Integer) jop.getValue();
    dialog.dispose();
    String password = null;
    if (result == JOptionPane.OK_OPTION) {
        password = new String(jpf.getPassword());
    }
    if (StringUtils.isEmpty(password)) {
        return null;
    } else {
        return password;
    }
}

From source file:com.gs.obevo.util.inputreader.DialogInputReader.java

@Override
public String readLine(String promptMessage) {
    final JTextField juf = new JTextField();
    JOptionPane juop = new JOptionPane(juf, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
    JDialog userDialog = juop.createDialog(promptMessage);
    userDialog.addComponentListener(new ComponentAdapter() {
        @Override// w  w w  . j  a  v a2 s.c  om
        public void componentShown(ComponentEvent e) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    juf.requestFocusInWindow();
                }
            });
        }
    });
    userDialog.setVisible(true);
    int uresult = (Integer) juop.getValue();
    userDialog.dispose();
    String userName = null;
    if (uresult == JOptionPane.OK_OPTION) {
        userName = new String(juf.getText());
    }

    if (StringUtils.isEmpty(userName)) {
        return null;
    } else {
        return userName;
    }
}

From source file:fxts.stations.transport.tradingapi.TradingServerSession.java

public void relogin() {
    if (mLogout) {
        return;//www  .  ja v a 2  s . c o m
    }
    final JDialog jd = TradeApp.getInst().getMainFrame().createWaitDialog("Session Lost...Reconnecting");
    jd.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentShown(ComponentEvent aEvent) {
            Thread worker = new Thread(new Runnable() {
                public void run() {
                    try {
                        TradingServerSession.getInstance().getGateway().relogin();
                        Liaison.getInstance().refresh();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        jd.dispose();
                        jd.setVisible(false);
                    }
                }
            });
            worker.start();
        }
    });
    jd.setVisible(true);
}

From source file:freemind.controller.Controller.java

public static Color showCommonJColorChooserDialog(Component component, String title, Color initialColor)
        throws HeadlessException {

    final JColorChooser pane = getCommonJColorChooser();
    pane.setColor(initialColor);/* ww  w . j  a v a  2  s. c o m*/

    ColorTracker ok = new ColorTracker(pane);
    JDialog dialog = JColorChooser.createDialog(component, title, true, pane, ok, null);
    dialog.addWindowListener(new Closer());
    dialog.addComponentListener(new DisposeOnClose());

    dialog.show(); // blocks until user brings dialog down...

    return ok.getColor();
}

From source file:net.rptools.maptool.client.functions.InputFunction.java

@Override
public Object childEvaluate(Parser parser, String functionName, List<Object> parameters)
        throws EvaluationException, ParserException {
    // 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;
        }//from ww w  .j a  v  a2  s. c o m
        // Multiple vars can be packed into a string, separated by "##"
        List<String> substrings = new ArrayList<String>();
        StrListFunctions.parse(paramStr, substrings, "##");
        for (String varString : substrings) {
            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 ParameterException(se.msg);
        } catch (InputType.OptionException oe) {
            throw new ParameterException(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 BigDecimal.ONE; // No work to do, so treat it as a successful invocation.

    // UI step 1 - First, see if a token is in context.
    VariableResolver varRes = parser.getVariableResolver();
    Token tokenInContext = null;
    if (varRes instanceof MapToolVariableResolver) {
        tokenInContext = ((MapToolVariableResolver) varRes).getTokenInContext();
    }
    String dialogTitle = "Input Values";
    if (tokenInContext != null) {
        String name = tokenInContext.getName(), gm_name = tokenInContext.getGMName();
        boolean isGM = MapTool.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(MapTool.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 BigDecimal.ZERO;

    // 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:
                        parser.setVariable(key + "_", value);
                        break;
                    case 2:
                        parser.setVariable(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) {
                parser.setVariable(vs.name, newValue.trim());
                allAssignments.append(vs.name + "=" + newValue.trim() + " ## ");
            }
        }
        if (cp.tabVarSpec != null) {
            parser.setVariable(cp.tabVarSpec.name, allAssignments.toString());
        }
    }

    return BigDecimal.ONE; // success

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

From source file:org.objectstyle.cayenne.modeler.pref.ComponentGeometry.java

/**
 * Binds this preference object to synchronize its state with a given component,
 * allowing to specify an initial offset compared to the stored position.
 *///w ww.  j  a  v a 2  s.  c  o m
public void bind(final JDialog dialog, int initialWidth, int initialHeight) {
    updateSize(dialog, initialWidth, initialHeight);

    dialog.addComponentListener(new ComponentAdapter() {

        public void componentResized(ComponentEvent e) {
            setWidth(new Integer(dialog.getWidth()));
            setHeight(new Integer(dialog.getHeight()));
        }
    });
}