使用JOptionPane进行数据验证 [英] Data validation with JOptionPane

查看:58
本文介绍了使用JOptionPane进行数据验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在JOptionPane上执行数据验证.我发现了以下方法,但我对此并不满意

I want to perform data validation while JOptionPane.I found the following approach but i am not really satisfied with it

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");
                }
        }
}

使用正则表达式来检测可以输入的字符而不是测试不能输入的字符会更好,更明智.

It would have been better and more sensible to use the regex to detect the characters that can be entered rather than testing for characters that can't be entered.

是否有更好,更简单的方法来使用JOptionPane进行数据验证? .我觉得这里的regex太过杀人了,如果我错了,请纠正我:P

Is there a better and simpler way to do data validation with JOptionPane ? . I feel regex is overkill here.Correct me if i am wrong:P

P.S我是Java的初学者

P.S i am a beginner with Java

推荐答案

长的答案是,使用DocumentFilter,请参见 DocumentFilter示例以获取更多详细信息.

The long answer is, use DocumentFilter, see Implementing a Document Filter and DocumentFilter Examples for more details.

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

The problem with this is, you need to take control, you can't rely on the "simple", "helper" functionality provided by JOptionPane.showInputDialog, as you need access to the text field been used to prompt the user...

例如...

以下示例使用 DocumentFilter示例

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;

public class ValidateTest {

    public static void main(String[] args) {
        JTextField field = new JTextField(20);
        Pattern p = Pattern.compile("[0-9]+");
        ((AbstractDocument) field.getDocument()).setDocumentFilter(new PatternFilter(p));
        int option = ask("Enter number:", field);
        if (option == JOptionPane.OK_OPTION) {
            System.out.println("You have entered " + field.getText());
        }
    }

    public static int ask(String label, JComponent comp) {

        JPanel panel = new JPanel();
        panel.add(new JLabel(label));
        panel.add(comp);

        return JOptionPane.showOptionDialog(null, panel, label, 
                        JOptionPane.OK_CANCEL_OPTION, 
                        JOptionPane.QUESTION_MESSAGE, null, null, null);

    }

    public static class PatternFilter extends DocumentFilter {

        // Useful for every kind of input validation !
        // this is the insert pattern
        // The pattern must contain all subpatterns so we can enter characters into a text component !
        private Pattern pattern;

        public PatternFilter(Pattern p) {
            pattern = p;
        }

        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
                        throws BadLocationException {

            String newStr = fb.getDocument().getText(0, fb.getDocument().getLength()) + string;
            Matcher m = pattern.matcher(newStr);
            if (m.matches()) {
                super.insertString(fb, offset, string, attr);
            } else {
            }
        }

        public void replace(FilterBypass fb, int offset,
                        int length, String string, AttributeSet attr) throws
                        BadLocationException {

            if (length > 0) {
                fb.remove(offset, length);
            }
            insertString(fb, offset, string, attr);
        }
    }

}

现在,通过一些巧妙的设计,您可以编写一个简单的帮助程序类,该类在内部构建所有这些内容,并提供一个不错的askFor(String label, Pattern p)样式方法,该方法可以返回String(如果用户取消了该操作,则返回null )

Now, with a little clever design, you could write a simple helper class which built all this internally and provided a nice askFor(String label, Pattern p) style method that could return a String (or null if the user canceled the operation)

这篇关于使用JOptionPane进行数据验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆