多个JTextfield的空字符串validation

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

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接受空字符串。 为什么是这样? 我希望也许可以抛出一个空字符串exception,我可以自定义validation消息,但由于空字段被接受,因此无法执行此操作。

谢谢

只是为了好玩,一个小小的手指抽搐展示了一个可重复使用的validation设置,它确实使用了核心Swing中可用的function。

合作者:

  • InputVerifier包含validation逻辑。 这里只是在validation字段中检查空文本。 注意
    • validation不得有副作用
    • 覆盖shouldYieldFocus以不限制焦点遍历
    • 它是所有文本字段的相同实例
  • 一个提交操作,通过显式调用inputVerifier(如果有)来检查其父级的所有子级的有效性,如果有任何无效则不执行任何操作
  • 一种非常简单但通常可用的错误消息的机制,它采用输入字段的标签

一些代码片段

 // 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的数组,我给出了一个概述

 JTextField[] fields = new JTextField[13] field[0] = firstname; field[1] = lastname; //then add remaining textfields for(int i = 0; i < fields.size(); ++i) { if(fields[i].getText().isEmpty()) JOptionPane.showMessageDialog(null, "No data entered"); } 

纠正我,如果我错了,我不熟悉Swing或awt.HTH 🙂

有多种方法可以做到这一点,一个是

  JTextField[] txtFieldA = new JTextField[13] ; txtFieldFirstName.setName("First Name") ; //add name for all text fields txtFieldA[0] = txtFieldFirstName ; txtFieldA[1] = txtFieldLastName ; .... // in action event for(JTextField txtField : txtFieldA) { if(txtField.getText().equals("") ) { JOptionPane.showMessageDialog(null, txtField.getName() +" is empty!"); //break it to avoid multiple popups break; } } 

另请参阅JGoodies Validation ,该框架可帮助您validationSwing应用程序中的用户输入,并帮助您报告validation错误和警告。

这是一种方法:

 public static boolean areAllNotEmpty(String... texts) { for(String s : texts) if(s == null || "".equals(s)) return false; return true; } // ... if(areAllNotEmpty(firstName, lastName, emailAddress, phone)) { JOptionPane.showMessageDialog(null, "No data entered"); }