Java 使用JOptionPane进行数据验证

Java 使用JOptionPane进行数据验证,java,swing,joptionpane,validation,Java,Swing,Joptionpane,Validation,我想在JOptionPane时执行数据验证 import javax.swing.*; import java.util.regex.*; public class ValidateJOptionPane { public static void main(String[] args) { String input = JOptionPane.showInputDialog("Enter number: "); Pattern p

我想在JOptionPane时执行数据验证

import javax.swing.*;
import java.util.regex.*;

public class ValidateJOptionPane {
        public static void main(String[] args) {
        String input = JOptionPane.showInputDialog("Enter number: ");
                Pattern p = Pattern.compile("[A-Z,a-z,&%$#@!()*^]");
                Matcher m = p.matcher(input);
                if (m.find()) {
             JOptionPane.showMessageDialog(null, "Please enter only numbers");
                }
        }
}
使用正则表达式来检测可以输入的字符,而不是测试不能输入的字符,会更好、更明智

有没有更好更简单的方法来使用JOptionPane进行数据验证。我觉得正则表达式在这里太过分了。如果我错了,请纠正我:P


p.S我是Java的初学者

详细的答案是,使用
DocumentFilter
,有关更多详细信息,请参阅和

问题是,您需要控制,您不能依赖于
JOptionPane.showInputDialog
提供的“简单”、“帮助器”功能,因为您需要访问用于提示用户的文本字段

例如

以下示例使用了来自的
PatternFilter
的(稍加修改的)版本

现在,通过一个巧妙的设计,您可以编写一个简单的助手类,它在内部构建了所有这些,并提供了一个漂亮的
askFor(stringlabel,Pattern p)
风格的方法,该方法可以返回
String
(或者
null
,如果用户取消了操作)

“使用正则表达式来检测可以输入的字符,而不是测试不能输入的字符,会更好、更明智。” 因此,您只需执行反向检查即可:

import javax.swing.*;
import java.util.regex.*;

public class ValidateJOptionPane {

  public static void main(String[] args) {
    String input = JOptionPane.showInputDialog("Enter number: ");
            Pattern p = Pattern.compile("^[0-9]*$");
            Matcher m = p.matcher(input);
            if (!m.find()) { // if pattern doesn't match (not found) 
             JOptionPane.showMessageDialog(null, "Please enter only numbers");
            }
    }
  }

[0-9]
表示数字0-9,
*
表示一些空格

你能解释一下你的正则表达式吗…我用了
[0-9]+
import javax.swing.*;
import java.util.regex.*;

public class ValidateJOptionPane {

  public static void main(String[] args) {
    String input = JOptionPane.showInputDialog("Enter number: ");
            Pattern p = Pattern.compile("^[0-9]*$");
            Matcher m = p.matcher(input);
            if (!m.find()) { // if pattern doesn't match (not found) 
             JOptionPane.showMessageDialog(null, "Please enter only numbers");
            }
    }
  }