多个JTextfield的空字符串验证

多个JTextfield的空字符串验证

本文介绍了多个JTextfield的空字符串验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有方法来验证一些JTextfields在java没有if else结构。我有一组13个字段,我想要一个错误消息,当没有给任何条目的任何13字段,并能够设置焦点到该特定的文本框。这是为了防止用户将空数据输入数据库。有人可以告诉我如果没有下面的if else结构,这可以实现。

Is there a way to validate a number of JTextfields in java without the if else structure. I have a set of 13 fields, i want an error message when no entry is given for any of the 13 fields and to be able to set focus to that particular textbox. this is to prevent users from entering empty data into database. could someone show me how this can be achieved without the if else structure like below.

if (firstName.equals("")) {
    JOptionPane.showMessageDialog(null, "No data entered");
} else if (lastName.equals("")) {
    JOptionPane.showMessageDialog(null, "No data entered");
} else if (emailAddress.equals("")) {
    JOptionPane.showMessageDialog(null, "No data entered");
} else if (phone.equals("")) {
   JOptionPane.showMessageDialog(null, "No data entered");
} else {
 //code to enter values into MySql database

上面的代码来自一个提交注册按钮的actionperformed方法a。尽管在MySQL中将字段设置为NOT NULL,空字符串从Java GUI被接受。为什么是这样?我希望也许一个空的字符串异常可以抛出,我可以自定义一个验证消息,但无法这样做,因为空字段被接受。

the above code come under the actionperformed method a of a submit registration button. despite setting fields in MySQL as NOT NULL, empty string were being accepted from java GUI. why is this? i was hoping perhaps an empty string exception could be thrown from which i could customise a validation message but was unable to do so as empty field were being accepted.

感谢

推荐答案

可重用的验证设置,它使用核心Swing中提供的功能。

Just for fun a little finger twitching demonstrating a re-usable validation setup which does use features available in core Swing.

合作者:


  • InputVerifier包含验证逻辑。这里只是检查验证字段中的空文本。注意

    • 验证不得有副作用

    • shouldYieldFocus被覆盖以不限制焦点遍历

    • 它是所有文本字段的相同实例

    一些代码段

    // a reusable, shareable input verifier
    InputVerifier iv = new InputVerifier() {
    
        @Override
        public boolean verify(JComponent input) {
            if (!(input instanceof JTextField)) return true;
            return isValidText((JTextField) input);
        }
    
        protected boolean isValidText(JTextField field) {
            return field.getText() != null &&
                    !field.getText().trim().isEmpty();
        }
    
        /**
         * Implemented to unconditionally return true: focus traversal
         * should never be restricted.
         */
        @Override
        public boolean shouldYieldFocus(JComponent input) {
            return true;
        }
    
    };
    // using MigLayout for lazyness ;-)
    final JComponent form = new JPanel(new MigLayout("wrap 2", "[align right][]"));
    for (int i = 0; i < 5; i++) {
        // instantiate the input fields with inputVerifier
        JTextField field = new JTextField(20);
        field.setInputVerifier(iv);
        // set label per field
        JLabel label = new JLabel("input " + i);
        label.setLabelFor(field);
        form.add(label);
        form.add(field);
    }
    
    Action validateForm = new AbstractAction("Commit") {
    
        @Override
        public void actionPerformed(ActionEvent e) {
            Component source = (Component) e.getSource();
            if (!validateInputs(source.getParent())) {
                // some input invalid, do nothing
                return;
            }
            System.out.println("all valid - do stuff");
        }
    
        protected boolean validateInputs(Container form) {
            for (int i = 0; i < form.getComponentCount(); i++) {
                JComponent child = (JComponent) form.getComponent(i);
                if (!isValid(child)) {
                    String text = getLabelText(child);
                    JOptionPane.showMessageDialog(form, "error at" + text);
                    child.requestFocusInWindow();
                    return false;
                }
            }
            return true;
        }
        /**
         * Returns the text of the label which is associated with
         * child.
         */
        protected String getLabelText(JComponent child) {
            JLabel labelFor = (JLabel) child.getClientProperty("labeledBy");
            return labelFor != null ? labelFor.getText() : "";
        }
    
        private boolean isValid(JComponent child) {
            if (child.getInputVerifier() != null) {
                return child.getInputVerifier().verify(child);
            }
            return true;
        }
    };
    // just for fun: MigLayout handles sequence of buttons
    // automagically as per OS guidelines
    form.add(new JButton("Cancel"), "tag cancel, span, split 2");
    form.add(new JButton(validateForm), "tag ok");
    

    这篇关于多个JTextfield的空字符串验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 12:02