Search in sources :

Example 6 with InputVerifier

use of javax.swing.InputVerifier in project vcell by virtualcell.

the class StochSimOptionsPanel method initConnections.

private void initConnections() {
    getCustomizedSeedRadioButton().addActionListener(ivjEventHandler);
    getRandomSeedRadioButton().addActionListener(ivjEventHandler);
    getTrajectoryButton().addActionListener(ivjEventHandler);
    getHistogramButton().addActionListener(ivjEventHandler);
    getJTextFieldCustomSeed().addFocusListener(ivjEventHandler);
    getJTextFieldNumOfTrials().addFocusListener(ivjEventHandler);
    getEpsilonTextField().addFocusListener(ivjEventHandler);
    getLambdaTextField().addFocusListener(ivjEventHandler);
    getMSRToleranceTextField().addFocusListener(ivjEventHandler);
    getSDEToleranceTextField().addFocusListener(ivjEventHandler);
    InputVerifier inputVerifier = new InputVerifier() {

        @Override
        public boolean verify(JComponent input) {
            return false;
        }

        @Override
        public boolean shouldYieldFocus(final JComponent input) {
            String text = ((JTextField) input).getText();
            boolean bValid = true;
            try {
                Double.parseDouble(text);
            } catch (NumberFormatException ex) {
                DialogUtils.showErrorDialog(StochSimOptionsPanel.this, ex.getMessage() + "Wrong number format " + ex.getMessage().toLowerCase());
                bValid = false;
            }
            if (bValid) {
                input.setBorder(UIManager.getBorder("TextField.border"));
            } else {
                input.setBorder(GuiConstants.ProblematicTextFieldBorder);
                SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                        input.requestFocus();
                    }
                });
            }
            return bValid;
        }
    };
    getJTextFieldCustomSeed().setInputVerifier(inputVerifier);
    getJTextFieldNumOfTrials().setInputVerifier(inputVerifier);
    getEpsilonTextField().setInputVerifier(inputVerifier);
    getLambdaTextField().setInputVerifier(inputVerifier);
    getMSRToleranceTextField().setInputVerifier(inputVerifier);
    getSDEToleranceTextField().setInputVerifier(inputVerifier);
}
Also used : JComponent(javax.swing.JComponent) JTextField(javax.swing.JTextField) InputVerifier(javax.swing.InputVerifier)

Example 7 with InputVerifier

use of javax.swing.InputVerifier in project CCDD by nasa.

the class CcddAssignMessageIDDialog method addMessageIDTab.

/**
 ********************************************************************************************
 * Add a tab for the specified table type or the telemetry message name/ID
 *
 * @param tabInfo
 *            message name/ID tab information reference
 *
 * @param isTlmName
 *            true if this is the tab for the telemetry message name assignment
 ********************************************************************************************
 */
private void addMessageIDTab(final MsgTabInfo tabInfo, final boolean isTlmName) {
    // Set the initial layout manager characteristics
    GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing(), ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing() / 2, ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing(), ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing() / 2), 0, 0);
    // Create sub-panels for the dialog components
    JPanel tabPnl = new JPanel(new GridBagLayout());
    JPanel inputPnl = new JPanel(new GridBagLayout());
    tabPnl.setBorder(etchBorder);
    // Check if this is the telemetry message name assignment tab
    if (isTlmName) {
        // Create the telemetry message name pattern label
        tabInfo.setPatternLbl(new JLabel("Name pattern"));
        tabInfo.getPatternLbl().setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
        inputPnl.add(tabInfo.getPatternLbl(), gbc);
        // Create the telemetry message name pattern field
        tabInfo.setPatternFld(new JTextField("Message_%03d", 12));
        tabInfo.getPatternFld().setFont(ModifiableFontInfo.INPUT_TEXT.getFont());
        tabInfo.getPatternFld().setEditable(true);
        tabInfo.getPatternFld().setForeground(ModifiableColorInfo.INPUT_TEXT.getColor());
        tabInfo.getPatternFld().setBackground(ModifiableColorInfo.INPUT_BACK.getColor());
        tabInfo.getPatternFld().setBorder(border);
        tabInfo.getPatternFld().setToolTipText(CcddUtilities.wrapText("<html>Format: <i>alphanumeric</i>#<i>&lt;alphanumeric&gt;", ModifiableSizeInfo.MAX_TOOL_TIP_LENGTH.getSize()));
        // Create an input field verifier for the pattern field
        tabInfo.getPatternFld().setInputVerifier(new InputVerifier() {

            // Storage for the last valid value entered; used to restore the pattern field
            // value if an invalid value is entered. Initialize to the value at the time the
            // field is created
            String lastValid = tabInfo.getPatternFld().getText();

            /**
             ********************************************************************************
             * Verify the contents of a the pattern field
             ********************************************************************************
             */
            @Override
            public boolean verify(JComponent input) {
                boolean isValid = true;
                // # is one or more digits
                if (!tabInfo.getPatternFld().getText().matches(InputDataType.MESSAGE_ID_NAME.getInputMatch() + "%(0\\d+)?d[a-zA-Z0-9_]*")) {
                    // Inform the user that the input value is invalid
                    new CcddDialogHandler().showMessageDialog(CcddAssignMessageIDDialog.this, "<html><b>Message name pattern must be in the format:<br><br></b>" + "&#160;&#160;&#160;<i>startText</i>%&lt;0#&gt;d<i>&lt;" + "endText&gt;</i><b><br><br>where </b><i>startText</i><b> " + "and </b><i>endText</i><b> consist of alphanumeric " + "characters and/or underscores, </b><i>startText</i><b> " + "begins with a letter or underscore, and </b><i>#</i><b> " + "is one or more digits.&#160;&#160;Note: </b><i>0#</i><b> " + "and </b><i>endText</i><b> are optional", "Missing/Invalid Input", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
                    // Restore the previous value in the field
                    tabInfo.getPatternFld().setText(lastValid);
                    // Set the flag indicating the input is invalid
                    isValid = false;
                    // Toggle the controls enable status so that the buttons are redrawn
                    // correctly
                    CcddAssignMessageIDDialog.this.setControlsEnabled(false);
                    CcddAssignMessageIDDialog.this.setControlsEnabled(true);
                } else // The value is valid
                {
                    // Clean up the field value
                    tabInfo.getPatternFld().setText(tabInfo.getPatternFld().getText().trim());
                    // Store the new value as the last valid value
                    lastValid = tabInfo.getPatternFld().getText();
                }
                return isValid;
            }
        });
        gbc.gridx++;
        inputPnl.add(tabInfo.getPatternFld(), gbc);
        gbc.gridx = 0;
        gbc.gridy++;
    }
    // Create the starting message number/ID label
    tabInfo.setStartLbl(new JLabel("Starting " + (isTlmName ? "number" : "ID")));
    tabInfo.getStartLbl().setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
    inputPnl.add(tabInfo.getStartLbl(), gbc);
    // Create the starting message number/ID field
    tabInfo.setStartFld(new JTextField((isTlmName ? "0" : "0x0"), 7));
    tabInfo.getStartFld().setFont(ModifiableFontInfo.INPUT_TEXT.getFont());
    tabInfo.getStartFld().setEditable(true);
    tabInfo.getStartFld().setForeground(ModifiableColorInfo.INPUT_TEXT.getColor());
    tabInfo.getStartFld().setBackground(ModifiableColorInfo.INPUT_BACK.getColor());
    tabInfo.getStartFld().setBorder(border);
    tabInfo.getStartFld().setToolTipText(isTlmName ? null : CcddUtilities.wrapText("<html>Format: <i>&lt;</i>0x<i>&gt;hexadecimal digits", ModifiableSizeInfo.MAX_TOOL_TIP_LENGTH.getSize()));
    // Create an input field verifier for the start field
    tabInfo.getStartFld().setInputVerifier(new InputVerifier() {

        // Storage for the last valid value entered; used to restore the start field value if
        // an invalid value is entered. Initialize to the value at the time the field is
        // created
        String lastValid = tabInfo.getStartFld().getText();

        /**
         ************************************************************************************
         * Verify the contents of a the start field
         ************************************************************************************
         */
        @Override
        public boolean verify(JComponent input) {
            boolean isValid = true;
            // Check if this is the telemetry message name assignment tab
            if (isTlmName) {
                // Check if the starting message number is not a non-negative integer
                if (!tabInfo.getStartFld().getText().matches(InputDataType.INT_NON_NEGATIVE.getInputMatch())) {
                    // Inform the user that the input value is invalid
                    new CcddDialogHandler().showMessageDialog(CcddAssignMessageIDDialog.this, "<html><b>Message starting number must be an integer >= 0", "Missing/Invalid Input", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
                    // Restore the previous value in the field
                    tabInfo.getStartFld().setText(lastValid);
                    // Set the flag indicating the input is invalid
                    isValid = false;
                    // Toggle the controls enable status so that the buttons are redrawn
                    // correctly
                    CcddAssignMessageIDDialog.this.setControlsEnabled(false);
                    CcddAssignMessageIDDialog.this.setControlsEnabled(true);
                } else // The value is valid
                {
                    // Clean up the field value
                    tabInfo.getStartFld().setText(InputDataType.INT_NON_NEGATIVE.formatInput(tabInfo.getStartFld().getText()));
                    // Store the new value as the last valid value
                    lastValid = tabInfo.getStartFld().getText();
                }
            } else // Not the telemetry message name assignment tab
            {
                // Check if the starting message ID value is not in hexadecimal format
                if (!tabInfo.getStartFld().getText().matches(InputDataType.HEXADECIMAL.getInputMatch())) {
                    // Inform the user that the input value is invalid
                    new CcddDialogHandler().showMessageDialog(CcddAssignMessageIDDialog.this, "<html><b>Starting ID must be in the format<br>&#160;&#160;<i>&lt;</i>" + "0x<i>&gt;</i>#<br>where # is one or more hexadecimal digits", "Missing/Invalid Input", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
                    // Restore the previous value in the field
                    tabInfo.getStartFld().setText(lastValid);
                    isValid = false;
                } else // The value is valid
                {
                    // Clean up the field value
                    tabInfo.getStartFld().setText(InputDataType.HEXADECIMAL.formatInput(tabInfo.getStartFld().getText()));
                    // Store the new value as the last valid value
                    lastValid = tabInfo.getStartFld().getText();
                }
            }
            return isValid;
        }
    });
    gbc.gridx++;
    inputPnl.add(tabInfo.getStartFld(), gbc);
    // Create the message name/ID interval label
    tabInfo.setIntervalLbl(new JLabel((isTlmName ? "Message" : "ID") + " interval"));
    tabInfo.getIntervalLbl().setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
    gbc.gridx = 0;
    gbc.gridy++;
    inputPnl.add(tabInfo.getIntervalLbl(), gbc);
    // Create the message number/ID interval field
    tabInfo.setIntervalFld(new JTextField("1", 5));
    tabInfo.getIntervalFld().setFont(ModifiableFontInfo.INPUT_TEXT.getFont());
    tabInfo.getIntervalFld().setEditable(true);
    tabInfo.getIntervalFld().setForeground(ModifiableColorInfo.INPUT_TEXT.getColor());
    tabInfo.getIntervalFld().setBackground(ModifiableColorInfo.INPUT_BACK.getColor());
    tabInfo.getIntervalFld().setBorder(border);
    // Create an input field verifier for the interval field
    tabInfo.getIntervalFld().setInputVerifier(new InputVerifier() {

        // Storage for the last valid value entered; used to restore the interval field value
        // if an invalid value is entered. Initialize to the value at the time the field is
        // created
        String lastValid = tabInfo.getIntervalFld().getText();

        /**
         ************************************************************************************
         * Verify the contents of a the interval field
         ************************************************************************************
         */
        @Override
        public boolean verify(JComponent input) {
            boolean isValid = true;
            // Check if the message ID interval value is not a positive integer
            if (!tabInfo.getIntervalFld().getText().matches(InputDataType.INT_POSITIVE.getInputMatch())) {
                // Inform the user that the input value is invalid
                new CcddDialogHandler().showMessageDialog(CcddAssignMessageIDDialog.this, "<html><b>ID interval must be a positive integer", "Missing/Invalid Input", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
                // Restore the previous value in the field
                tabInfo.getIntervalFld().setText(lastValid);
                // Set the flag indicating the input is invalid
                isValid = false;
                // Toggle the controls enable status so that the buttons are redrawn
                // correctly
                CcddAssignMessageIDDialog.this.setControlsEnabled(false);
                CcddAssignMessageIDDialog.this.setControlsEnabled(true);
            } else // The value is valid
            {
                // Clean up the field value
                tabInfo.getIntervalFld().setText(InputDataType.INT_POSITIVE.formatInput(tabInfo.getIntervalFld().getText()));
                // Store the new value as the last valid value
                lastValid = tabInfo.getIntervalFld().getText();
            }
            return isValid;
        }
    });
    gbc.gridx++;
    inputPnl.add(tabInfo.getIntervalFld(), gbc);
    // Create the check box to enable message name/ID assignment
    tabInfo.setAssignCbx(new JCheckBox("Assign " + tabInfo.getType() + " message " + (isTlmName ? "names" : "IDs")));
    tabInfo.getAssignCbx().setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
    // Add a listener for check box selection changes
    tabInfo.getAssignCbx().addItemListener(new ItemListener() {

        /**
         ************************************************************************************
         * Set the remaining inputs based on the check box selection state
         ************************************************************************************
         */
        @Override
        public void itemStateChanged(ItemEvent ae) {
            setTabGUIComponentsEnable(tabInfo, tabInfo.getAssignCbx().isSelected());
        }
    });
    gbc.insets.top = ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() / 2;
    gbc.insets.bottom = ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() / 2;
    gbc.gridx = 0;
    gbc.gridy = 0;
    tabPnl.add(tabInfo.getAssignCbx(), gbc);
    // Add the input panel to the tab panel
    gbc.insets.left = ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing() * 2;
    gbc.gridy++;
    tabPnl.add(inputPnl, gbc);
    // Create the overwrite existing name/IDs check box
    tabInfo.setOverwriteCbx(new JCheckBox("Overwrite existing " + (isTlmName ? "names" : "IDs")));
    tabInfo.getOverwriteCbx().setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
    gbc.gridy++;
    tabPnl.add(tabInfo.getOverwriteCbx(), gbc);
    // Add the tab
    tabbedPane.addTab(tabInfo.getName(), null, tabPnl, tabInfo.getToolTip());
    // Disable the tab components initially
    setTabGUIComponentsEnable(tabInfo, false);
}
Also used : JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) ItemEvent(java.awt.event.ItemEvent) Insets(java.awt.Insets) GridBagLayout(java.awt.GridBagLayout) JComponent(javax.swing.JComponent) JLabel(javax.swing.JLabel) JTextField(javax.swing.JTextField) InputVerifier(javax.swing.InputVerifier) JCheckBox(javax.swing.JCheckBox) ItemListener(java.awt.event.ItemListener)

Example 8 with InputVerifier

use of javax.swing.InputVerifier in project CCDD by nasa.

the class CcddPreferencesDialog method addSpacingTab.

/**
 ********************************************************************************************
 * Add the spacing update tab to the tabbed pane
 ********************************************************************************************
 */
private void addSpacingTab() {
    // Set the initial layout manager characteristics
    GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH, new Insets(ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing(), ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing() / 2, ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing(), ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing() / 2), 0, 0);
    // Create a border for the input fields
    Border border = BorderFactory.createCompoundBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, Color.GRAY), BorderFactory.createEmptyBorder(ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing(), ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing(), ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing(), ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing()));
    // Create storage for the description and input field representing each modifiable spacing
    JLabel[] spacingLbl = new JLabel[ModifiableSpacingInfo.values().length];
    JButton[] spacingBtn = new JButton[ModifiableSpacingInfo.values().length];
    spacingFld = new JTextField[ModifiableSpacingInfo.values().length];
    // Create a panel to contain the spacing components
    JPanel innerSpacingPnl = new JPanel(new GridBagLayout());
    innerSpacingPnl.setBorder(emptyBorder);
    // Use an outer panel so that the components can be forced to the top of the tab area
    JPanel spacingPnl = new JPanel(new BorderLayout());
    spacingPnl.setBorder(emptyBorder);
    spacingPnl.add(innerSpacingPnl, BorderLayout.PAGE_START);
    // Create a scroll pane in which to display the spacing labels and fields
    JScrollPane spacingScrollPane = new JScrollPane(spacingPnl);
    spacingScrollPane.setBorder(emptyBorder);
    spacingScrollPane.setViewportBorder(emptyBorder);
    // Add the note to the panel
    JLabel noteLbl = new JLabel("<html><i>Note: Open windows must be closed and " + "reopened for spacing changes to take effect");
    noteLbl.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
    noteLbl.setForeground(ModifiableColorInfo.SPECIAL_LABEL_TEXT.getColor());
    noteLbl.setBorder(BorderFactory.createEmptyBorder(ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() * 2, ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing() / 2, ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing(), ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing()));
    // Create a panel to contain the scroll pane and a note with fixed position at the bottom
    // of the panel
    JPanel scrollAndNotePnl = new JPanel(new BorderLayout());
    scrollAndNotePnl.add(spacingScrollPane, BorderLayout.CENTER);
    scrollAndNotePnl.add(noteLbl, BorderLayout.PAGE_END);
    // Add the spacing update tab to the tabbed pane
    tabbedPane.addTab(SPACING, null, scrollAndNotePnl, "Change program spacing values");
    // Create a listener for the default spacing buttons
    ActionListener defaultListener = new ActionListener() {

        /**
         ************************************************************************************
         * Update the spacing to the default value
         ************************************************************************************
         */
        @Override
        public void actionPerformed(ActionEvent ae) {
            // Get the index of the spacing field array, which is stored as the button's name
            int index = Integer.valueOf(((JButton) ae.getSource()).getName());
            // Set the spacing to its default value
            spacingFld[index].setText(String.valueOf(ModifiableSpacingInfo.values()[index].getDefault()));
        }
    };
    int index = 0;
    // Step through each modifiable spacing
    for (final ModifiableSpacingInfo modSpacing : ModifiableSpacingInfo.values()) {
        // Create the spacing label and input field
        spacingLbl[index] = new JLabel(modSpacing.getName() + " (" + modSpacing.getMinimum() + ", " + modSpacing.getMaximum() + ")");
        spacingLbl[index].setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
        spacingLbl[index].setToolTipText(CcddUtilities.wrapText(modSpacing.getDescription(), ModifiableSizeInfo.MAX_TOOL_TIP_LENGTH.getSize()));
        innerSpacingPnl.add(spacingLbl[index], gbc);
        spacingFld[index] = new JTextField(String.valueOf(modSpacing.getSpacing()), 3);
        spacingFld[index].setFont(ModifiableFontInfo.INPUT_TEXT.getFont());
        spacingFld[index].setForeground(ModifiableColorInfo.INPUT_TEXT.getColor());
        spacingFld[index].setBackground(ModifiableColorInfo.INPUT_BACK.getColor());
        spacingFld[index].setBorder(border);
        spacingFld[index].setName(modSpacing.getPreferenceKey());
        spacingFld[index].setToolTipText(CcddUtilities.wrapText(modSpacing.getDescription(), ModifiableSizeInfo.MAX_TOOL_TIP_LENGTH.getSize()));
        // Create an input verifier to keep the spacing value within its specified limits
        spacingFld[index].setInputVerifier(new InputVerifier() {

            // Storage for the last valid value entered; used to restore the spacing value if
            // an invalid value is entered
            String lastValid = String.valueOf(modSpacing.getSpacing());

            /**
             ********************************************************************************
             * Verify the contents of a the spacing field
             ********************************************************************************
             */
            @Override
            public boolean verify(JComponent input) {
                boolean isValid = true;
                JTextField spacingFld = (JTextField) input;
                try {
                    // Get the reference to the modifiable spacing information using its
                    // program preferences key, which is stored as the field's name
                    ModifiableSpacingInfo modSpacing = ModifiableSpacingInfo.getModifiableSpacingInfo(input.getName());
                    // Remove any leading or trailing white space characters
                    String spacing = spacingFld.getText().trim();
                    // Check if the spacing field is empty
                    if (spacing.isEmpty()) {
                        throw new CCDDException(modSpacing.getName() + "<b>' cannot be blank");
                    }
                    // Check if the spacing value isn't a positive integer
                    if (!spacing.matches(InputDataType.INT_POSITIVE.getInputMatch())) {
                        throw new CCDDException(modSpacing.getName() + "<b>' must be a positive integer value");
                    }
                    // Convert the text to an integer
                    int currentValue = Integer.valueOf(spacing);
                    // Check if the spacing value is outside of its specified limits
                    if (currentValue < modSpacing.getMinimum() || currentValue > modSpacing.getMaximum()) {
                        throw new CCDDException(modSpacing.getName() + "<b>' is outside allowable limits");
                    }
                    // Update the spacing field to the new (valid) value
                    spacingFld.setText(spacing);
                    // Store the new value as the last valid value
                    lastValid = spacingFld.getText();
                } catch (CCDDException ce) {
                    // Inform the user that the input value is invalid
                    new CcddDialogHandler().showMessageDialog(CcddPreferencesDialog.this, "<html><b>The value for '</b>" + ce.getMessage(), "Missing/Invalid Input", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
                    // Restore the spacing field to the last valid value
                    spacingFld.setText(lastValid);
                    // Set the flag to indicate the spacing value is invalid
                    isValid = false;
                    // Toggle the controls enable status so that the buttons are redrawn
                    // correctly
                    CcddPreferencesDialog.this.setControlsEnabled(false);
                    CcddPreferencesDialog.this.setControlsEnabled(true);
                }
                return isValid;
            }
        });
        // Add the spacing field to the spacing panel
        gbc.gridx++;
        innerSpacingPnl.add(spacingFld[index], gbc);
        // Create a button for setting the spacing to its default value and add it to the
        // spacing panel
        spacingBtn[index] = new JButton("Default (" + modSpacing.getDefault() + ")");
        spacingBtn[index].setFont(ModifiableFontInfo.DIALOG_BUTTON.getFont());
        spacingBtn[index].setName(String.valueOf(index));
        spacingBtn[index].addActionListener(defaultListener);
        gbc.gridx++;
        innerSpacingPnl.add(spacingBtn[index], gbc);
        gbc.weightx = 1.0;
        gbc.gridx++;
        innerSpacingPnl.add(new JLabel(""), gbc);
        gbc.weightx = 0.0;
        gbc.gridx = 0;
        gbc.gridy++;
        index++;
    }
    // Set the scroll bar scroll increment
    spacingScrollPane.getVerticalScrollBar().setUnitIncrement(spacingFld[0].getPreferredSize().height / 2 + ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing());
    // Calculate the maximum required height of the panel containing the spacing labels and
    // fields (= # of rows * row height)
    maxScrollPaneHeight = Math.max(maxScrollPaneHeight, 10 * spacingScrollPane.getPreferredSize().height / spacingFld.length);
}
Also used : JScrollPane(javax.swing.JScrollPane) JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) Insets(java.awt.Insets) CCDDException(CCDD.CcddClassesDataTable.CCDDException) GridBagLayout(java.awt.GridBagLayout) ActionEvent(java.awt.event.ActionEvent) JButton(javax.swing.JButton) JComponent(javax.swing.JComponent) JLabel(javax.swing.JLabel) JTextField(javax.swing.JTextField) InputVerifier(javax.swing.InputVerifier) BorderLayout(java.awt.BorderLayout) ActionListener(java.awt.event.ActionListener) ModifiableSpacingInfo(CCDD.CcddConstants.ModifiableSpacingInfo) Border(javax.swing.border.Border) BevelBorder(javax.swing.border.BevelBorder)

Example 9 with InputVerifier

use of javax.swing.InputVerifier in project CCDD by nasa.

the class CcddPreferencesDialog method addSizeTab.

/**
 ********************************************************************************************
 * Add the size update tab to the tabbed pane
 ********************************************************************************************
 */
private void addSizeTab() {
    // Set the initial layout manager characteristics
    GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH, new Insets(ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing(), ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing() / 2, ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing(), ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing() / 2), 0, 0);
    // Create a border for the input fields
    Border border = BorderFactory.createCompoundBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, Color.GRAY), BorderFactory.createEmptyBorder(ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing(), ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing(), ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing(), ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing()));
    // Create storage for the description and input field representing each modifiable size
    JLabel[] sizeLbl = new JLabel[ModifiableSizeInfo.values().length];
    JButton[] sizeBtn = new JButton[ModifiableSizeInfo.values().length];
    sizeFld = new JTextField[ModifiableSizeInfo.values().length];
    // Create a panel to contain the size components
    JPanel innerSizePnl = new JPanel(new GridBagLayout());
    innerSizePnl.setBorder(emptyBorder);
    // Use an outer panel so that the components can be forced to the top of the tab area
    JPanel sizePnl = new JPanel(new BorderLayout());
    sizePnl.setBorder(emptyBorder);
    sizePnl.add(innerSizePnl, BorderLayout.PAGE_START);
    // Create a scroll pane in which to display the size labels and fields
    JScrollPane sizeScrollPane = new JScrollPane(sizePnl);
    sizeScrollPane.setBorder(emptyBorder);
    sizeScrollPane.setViewportBorder(emptyBorder);
    // Add the size update tab to the tabbed pane
    tabbedPane.addTab(SIZE, null, sizeScrollPane, "Change program maximum width and length values");
    // Create a listener for the default size buttons
    ActionListener defaultListener = new ActionListener() {

        /**
         ************************************************************************************
         * Update the size to the default value
         ************************************************************************************
         */
        @Override
        public void actionPerformed(ActionEvent ae) {
            // Get the index of the size field array, which is stored as the button's name
            int index = Integer.valueOf(((JButton) ae.getSource()).getName());
            // Set the size to its default value
            sizeFld[index].setText(String.valueOf(ModifiableSizeInfo.values()[index].getDefault()));
        }
    };
    int index = 0;
    // Step through each modifiable size
    for (final ModifiableSizeInfo modSize : ModifiableSizeInfo.values()) {
        // Create the size label and input field
        sizeLbl[index] = new JLabel(modSize.getName() + " (" + modSize.getMinimum() + ", " + modSize.getMaximum() + ")");
        sizeLbl[index].setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
        sizeLbl[index].setToolTipText(CcddUtilities.wrapText(modSize.getDescription(), ModifiableSizeInfo.MAX_TOOL_TIP_LENGTH.getSize()));
        innerSizePnl.add(sizeLbl[index], gbc);
        sizeFld[index] = new JTextField(String.valueOf(modSize.getSize()), 3);
        sizeFld[index].setFont(ModifiableFontInfo.INPUT_TEXT.getFont());
        sizeFld[index].setForeground(ModifiableColorInfo.INPUT_TEXT.getColor());
        sizeFld[index].setBackground(ModifiableColorInfo.INPUT_BACK.getColor());
        sizeFld[index].setBorder(border);
        sizeFld[index].setName(modSize.getPreferenceKey());
        sizeFld[index].setToolTipText(CcddUtilities.wrapText(modSize.getDescription(), ModifiableSizeInfo.MAX_TOOL_TIP_LENGTH.getSize()));
        // Create an input verifier to keep the size value within its specified limits
        sizeFld[index].setInputVerifier(new InputVerifier() {

            // Storage for the last valid value entered; used to restore the size value if an
            // invalid value is entered
            String lastValid = String.valueOf(modSize.getSize());

            /**
             ********************************************************************************
             * Verify the contents of a the size field
             ********************************************************************************
             */
            @Override
            public boolean verify(JComponent input) {
                boolean isValid = true;
                JTextField sizeFld = (JTextField) input;
                try {
                    // Get the reference to the modifiable size information using its program
                    // preferences key, which is stored as the field's name
                    ModifiableSizeInfo modSize = ModifiableSizeInfo.getModifiableSizeInfo(input.getName());
                    // Remove any leading or trailing white space characters
                    String size = sizeFld.getText().trim();
                    // Check if the size field is empty
                    if (size.isEmpty()) {
                        throw new CCDDException(modSize.getName() + "<b>' cannot be blank");
                    }
                    // Check if the size value isn't a positive integer
                    if (!size.matches(InputDataType.INT_POSITIVE.getInputMatch())) {
                        throw new CCDDException(modSize.getName() + "<b>' must be a positive integer value");
                    }
                    // Convert the text to an integer
                    int currentValue = Integer.valueOf(size);
                    // Check if the size value is outside of its specified limits
                    if (currentValue < modSize.getMinimum() || currentValue > modSize.getMaximum()) {
                        throw new CCDDException(modSize.getName() + "<b>' is outside allowable limits");
                    }
                    // Update the size field to the new (valid) value
                    sizeFld.setText(size);
                    // Store the new value as the last valid value
                    lastValid = sizeFld.getText();
                } catch (CCDDException ce) {
                    // Inform the user that the input value is invalid
                    new CcddDialogHandler().showMessageDialog(CcddPreferencesDialog.this, "<html><b>The value for '</b>" + ce.getMessage(), "Missing/Invalid Input", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
                    // Restore the size field to the last valid value
                    sizeFld.setText(lastValid);
                    // Set the flag to indicate the size value is invalid
                    isValid = false;
                    // Toggle the controls enable status so that the buttons are redrawn
                    // correctly
                    CcddPreferencesDialog.this.setControlsEnabled(false);
                    CcddPreferencesDialog.this.setControlsEnabled(true);
                }
                return isValid;
            }
        });
        // Add the size field to the size panel
        gbc.gridx++;
        innerSizePnl.add(sizeFld[index], gbc);
        // Create a button for setting the size to its default value and add it to the size
        // panel
        sizeBtn[index] = new JButton("Default (" + modSize.getDefault() + ")");
        sizeBtn[index].setFont(ModifiableFontInfo.DIALOG_BUTTON.getFont());
        sizeBtn[index].setName(String.valueOf(index));
        sizeBtn[index].addActionListener(defaultListener);
        gbc.gridx++;
        innerSizePnl.add(sizeBtn[index], gbc);
        gbc.weightx = 1.0;
        gbc.gridx++;
        innerSizePnl.add(new JLabel(""), gbc);
        gbc.weightx = 0.0;
        gbc.gridx = 0;
        gbc.gridy++;
        index++;
    }
    // Set the scroll bar scroll increment
    sizeScrollPane.getVerticalScrollBar().setUnitIncrement(sizeFld[0].getPreferredSize().height / 2 + ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing());
    // Calculate the maximum required height of the panel containing the size labels and fields
    // (= # of rows * row height)
    maxScrollPaneHeight = Math.max(maxScrollPaneHeight, 10 * sizeScrollPane.getPreferredSize().height / sizeFld.length);
}
Also used : JScrollPane(javax.swing.JScrollPane) JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) Insets(java.awt.Insets) CCDDException(CCDD.CcddClassesDataTable.CCDDException) GridBagLayout(java.awt.GridBagLayout) ActionEvent(java.awt.event.ActionEvent) JButton(javax.swing.JButton) JComponent(javax.swing.JComponent) JLabel(javax.swing.JLabel) JTextField(javax.swing.JTextField) InputVerifier(javax.swing.InputVerifier) BorderLayout(java.awt.BorderLayout) ActionListener(java.awt.event.ActionListener) ModifiableSizeInfo(CCDD.CcddConstants.ModifiableSizeInfo) Border(javax.swing.border.Border) BevelBorder(javax.swing.border.BevelBorder)

Example 10 with InputVerifier

use of javax.swing.InputVerifier in project CCDD by nasa.

the class CcddInputFieldPanelHandler method createDataFieldPanel.

/**
 ********************************************************************************************
 * Create the data fields for display in the description and data field panel
 *
 * @param undoable
 *            true if the change(s) to the data fields should be stored for possible undo/redo
 *            operations; false to not store the changes
 ********************************************************************************************
 */
protected void createDataFieldPanel(boolean undoable) {
    maxFieldWidth = 0;
    // Set the preferred size so that the layout manager uses its default sizing
    fieldPnlHndlrOwner.setPreferredSize(null);
    // Check if the data fields are already displayed
    if (fieldPnl != null) {
        // Remove the existing data fields
        inputPnl.remove(fieldPnl);
    }
    // Check if this is a data table
    if (isDataTable) {
        // Build the data field information so that only applicable fields are displayed
        dataFieldHandler.buildFieldInformation(((CcddTableEditorHandler) this).getTableInformation().getTablePath(), ((CcddTableEditorHandler) this).getTableInformation().isRootStructure(), false);
    }
    // Check if any data fields exist
    if (dataFieldHandler.getFieldInformation() != null && !dataFieldHandler.getFieldInformation().isEmpty()) {
        // Create a panel to contain the data fields. As the editor is resized the field panel
        // is resized to contain the data fields, wrapping them to new lines as needed
        fieldPnl = new JPanel(new WrapLayout(FlowLayout.LEADING));
        // Adjust the border to align the first field with the description label
        fieldPnl.setBorder(BorderFactory.createEmptyBorder(-ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing(), -ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing(), 0, 0));
        // Step through each data field
        for (final FieldInformation fieldInfo : dataFieldHandler.getFieldInformation()) {
            switch(fieldInfo.getInputType().getInputFormat()) {
                case PAGE_FORMAT:
                    switch(fieldInfo.getInputType()) {
                        case BREAK:
                            // Create a text field for the separator so it can be handled like
                            // other fields
                            fieldInfo.setInputFld(undoHandler.new UndoableTextField());
                            // Add a vertical separator to the field panel
                            fieldPnl.add(new JSeparator(SwingConstants.VERTICAL));
                            break;
                        case SEPARATOR:
                            // Create a text field for the separator so it can be handled like
                            // other fields
                            fieldInfo.setInputFld(undoHandler.new UndoableTextField());
                            // Add a horizontal separator to the field panel
                            fieldPnl.add(new JSeparator());
                            break;
                        default:
                            break;
                    }
                    break;
                case BOOLEAN:
                    // Create the data field check box
                    fieldInfo.setInputFld(undoHandler.new UndoableCheckBox(fieldInfo.getFieldName(), Boolean.valueOf(fieldInfo.getValue())));
                    UndoableCheckBox booleanCb = (UndoableCheckBox) fieldInfo.getInputFld();
                    booleanCb.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
                    booleanCb.setForeground(ModifiableColorInfo.SPECIAL_LABEL_TEXT.getColor());
                    // Set the check box's name so that the undo handler can identify the check
                    // box, even if it's destroyed and recreated
                    booleanCb.setName(fieldInfo.getOwnerName() + DATA_FIELD_IDENTIFIER_SEPARATOR + fieldInfo.getFieldName());
                    // Adjust the left and right padding around the check box so that it is
                    // spaced the same as a text field data field
                    booleanCb.setBorder(BorderFactory.createEmptyBorder(0, ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing(), 0, ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing()));
                    // Check if a description exists for this field
                    if (!fieldInfo.getDescription().isEmpty()) {
                        // Set the description as the tool tip text for this check box
                        booleanCb.setToolTipText(CcddUtilities.wrapText(fieldInfo.getDescription(), ModifiableSizeInfo.MAX_TOOL_TIP_LENGTH.getSize()));
                    }
                    // And the check box to the field panel
                    fieldPnl.add(booleanCb);
                    // Store this check box's width if it is the largest data field width
                    maxFieldWidth = Math.max(maxFieldWidth, booleanCb.getPreferredSize().width);
                    break;
                default:
                    final JTextComponent inputFld;
                    // Create a panel for a single label and text field pair. This is necessary
                    // so that the two will stay together if line wrapping occurs due to a
                    // window size change
                    JPanel singleFldPnl = new JPanel(new FlowLayout(FlowLayout.LEADING, ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing(), ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() / 4));
                    singleFldPnl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
                    // Create the data field label
                    JLabel fieldLbl = new JLabel(fieldInfo.getFieldName());
                    fieldLbl.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
                    fieldLbl.setForeground(ModifiableColorInfo.SPECIAL_LABEL_TEXT.getColor());
                    singleFldPnl.add(fieldLbl);
                    // Check if the input type is for multi-line text
                    if (fieldInfo.getInputType().equals(InputDataType.TEXT_MULTI)) {
                        // Create the data field input field as a text area, which allows new
                        // line characters which cause the field to be displayed in multiple
                        // rows
                        fieldInfo.setInputFld(undoHandler.new UndoableTextArea(fieldInfo.getValue(), 1, fieldInfo.getSize()));
                        inputFld = (UndoableTextArea) fieldInfo.getInputFld();
                    } else // The input type is one other than for multi-line text
                    {
                        // Create the data field input field as a text field, which allows a
                        // single rows
                        fieldInfo.setInputFld(undoHandler.new UndoableTextField(fieldInfo.getValue(), fieldInfo.getSize()));
                        inputFld = (UndoableTextField) fieldInfo.getInputFld();
                    }
                    inputFld.setFont(ModifiableFontInfo.INPUT_TEXT.getFont());
                    inputFld.setEditable(true);
                    inputFld.setBorder(border);
                    inputFld.setForeground(ModifiableColorInfo.INPUT_TEXT.getColor());
                    inputFld.setBackground(fieldInfo.getValue().isEmpty() && fieldInfo.isRequired() ? ModifiableColorInfo.REQUIRED_BACK.getColor() : ModifiableColorInfo.INPUT_BACK.getColor());
                    // Set the text field's name so that the undo handler can identify the text
                    // field, even if it's destroyed and recreated
                    inputFld.setName(fieldInfo.getOwnerName() + DATA_FIELD_IDENTIFIER_SEPARATOR + fieldInfo.getFieldName());
                    // Check if a description exists for this field
                    if (!fieldInfo.getDescription().isEmpty()) {
                        // Set the description as the tool tip text for this text field
                        inputFld.setToolTipText(CcddUtilities.wrapText(fieldInfo.getDescription(), ModifiableSizeInfo.MAX_TOOL_TIP_LENGTH.getSize()));
                    }
                    // Add the data field to the single field panel
                    singleFldPnl.add(inputFld);
                    // And the single field to the field panel
                    fieldPnl.add(singleFldPnl);
                    // Store this field's width if it is the largest data field width
                    maxFieldWidth = Math.max(maxFieldWidth, singleFldPnl.getPreferredSize().width);
                    // Create an input field verifier for the data field
                    inputFld.setInputVerifier(new InputVerifier() {

                        // Storage for the last valid value entered; used to restore the data
                        // field value if an invalid value is entered. Initialize to the value
                        // at the time the field is created
                        String lastValid = inputFld.getText();

                        /**
                         ********************************************************************
                         * Verify the contents of a the data field
                         ********************************************************************
                         */
                        @Override
                        public boolean verify(JComponent input) {
                            boolean isValid = true;
                            // Get the data field reference to shorten subsequent calls
                            JTextComponent inFld = (JTextComponent) input;
                            // Get the data field contents
                            String inputTxt = inFld.getText();
                            // trailing white space characters
                            if (fieldInfo.getInputType() != InputDataType.TEXT_WHT_SPC && fieldInfo.getInputType() != InputDataType.TEXT_MULTI_WHT_SPC) {
                                // Remove leading and trailing white space characters
                                inputTxt = inputTxt.trim();
                            }
                            // Check if the field contains an illegal character
                            if (!fieldInfo.getInputType().getInputMatch().isEmpty() && !inputTxt.isEmpty() && !inputTxt.matches(fieldInfo.getInputType().getInputMatch())) {
                                // Inform the user that the data field contents is invalid
                                new CcddDialogHandler().showMessageDialog(fieldPnlHndlrOwner, "<html><b>Invalid characters in field '</b>" + fieldInfo.getFieldName() + "<b>'; characters consistent with input type '" + fieldInfo.getInputType().getInputName() + "' expected", "Invalid " + fieldInfo.getInputType().getInputName(), JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
                                // redrawn correctly
                                if (fieldPnlHndlrOwner instanceof CcddFrameHandler) {
                                    ((CcddFrameHandler) fieldPnlHndlrOwner).setControlsEnabled(false);
                                    ((CcddFrameHandler) fieldPnlHndlrOwner).setControlsEnabled(true);
                                } else if (fieldPnlHndlrOwner instanceof CcddDialogHandler) {
                                    ((CcddDialogHandler) fieldPnlHndlrOwner).setControlsEnabled(false);
                                    ((CcddDialogHandler) fieldPnlHndlrOwner).setControlsEnabled(true);
                                }
                                // Check if the data field is a text field
                                if (input instanceof UndoableTextField) {
                                    // Restore the previous value in the data field
                                    ((UndoableTextField) inFld).setText(lastValid, false);
                                } else // Check if the data field is a text area (multi-line)
                                if (input instanceof UndoableTextArea) {
                                    // Restore the previous value in the data field
                                    ((UndoableTextArea) inFld).setText(lastValid);
                                }
                                // Set the flag to indicate an invalid value was entered
                                isValid = false;
                            } else // The input is valid
                            {
                                // Store the 'cleaned' text back into the text field. For
                                // numeric types, reformat the input value
                                inFld.setText(fieldInfo.getInputType().formatInput(inputTxt));
                                fieldInfo.setValue(inFld.getText());
                                // Store the new value as the last valid value
                                lastValid = inFld.getText();
                                // Set the text field background color. If the field is empty
                                // and is flagged as required then set the background to
                                // indicate a value should be supplied
                                setFieldBackground(fieldInfo);
                            }
                            return isValid;
                        }
                    });
                    break;
            }
        }
        // Check that at least one field exists
        if (fieldPnl.getComponentCount() != 0) {
            // Add the data field panel to the dialog
            inputPnl.add(fieldPnl, gbc);
        }
    }
    // Check if this is a data table
    if (isDataTable) {
        // Build the data field information so that all fields are included
        dataFieldHandler.buildFieldInformation(((CcddTableEditorHandler) this).getTableInformation().getTablePath(), ((CcddTableEditorHandler) this).getTableInformation().isRootStructure(), true);
    }
    // Check if the data field panel change should be put in the undo/redo stack
    if (undoable) {
        // Store the field information in the undo handler in case the update needs to be
        // undone
        undoFieldPnl.addDataFieldEdit(this, dataFieldHandler.getFieldInformationCopy());
    }
    // Force the owner of the editor panel to redraw so that changes to the fields are
    // displayed and the owner's size is adjusted
    fieldPnlHndlrOwner.revalidate();
    fieldPnlHndlrOwner.repaint();
}
Also used : JPanel(javax.swing.JPanel) FlowLayout(java.awt.FlowLayout) JComponent(javax.swing.JComponent) JLabel(javax.swing.JLabel) JTextComponent(javax.swing.text.JTextComponent) UndoableTextField(CCDD.CcddUndoHandler.UndoableTextField) InputVerifier(javax.swing.InputVerifier) WrapLayout(CCDD.CcddClassesComponent.WrapLayout) JSeparator(javax.swing.JSeparator) UndoableCheckBox(CCDD.CcddUndoHandler.UndoableCheckBox) UndoableTextArea(CCDD.CcddUndoHandler.UndoableTextArea) FieldInformation(CCDD.CcddClassesDataTable.FieldInformation)

Aggregations

InputVerifier (javax.swing.InputVerifier)11 JComponent (javax.swing.JComponent)11 JTextField (javax.swing.JTextField)9 JLabel (javax.swing.JLabel)8 JPanel (javax.swing.JPanel)7 Insets (java.awt.Insets)6 GridBagConstraints (java.awt.GridBagConstraints)5 GridBagLayout (java.awt.GridBagLayout)5 ActionEvent (java.awt.event.ActionEvent)4 ActionListener (java.awt.event.ActionListener)4 JScrollPane (javax.swing.JScrollPane)4 BorderLayout (java.awt.BorderLayout)3 FlowLayout (java.awt.FlowLayout)3 JButton (javax.swing.JButton)3 CCDDException (CCDD.CcddClassesDataTable.CCDDException)2 KeyAdapter (java.awt.event.KeyAdapter)2 KeyEvent (java.awt.event.KeyEvent)2 JCheckBox (javax.swing.JCheckBox)2 JTextArea (javax.swing.JTextArea)2 BevelBorder (javax.swing.border.BevelBorder)2