在jtextfield中评估“价格"的正则表达式是什么 [英] What is the regular expression for valdating a 'price' in a jtextfield

查看:89
本文介绍了在jtextfield中评估“价格"的正则表达式是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户输入某些商品的价格时验证jtextfield.

我有一个完美的工作代码,如果用户输入的某些字符与正则表达式不匹配,则会发出蜂鸣声并丢弃.(对于正则表达式[[0-9] +,它接受任意数量的数字并发出蜂鸣声作为输入)

但是问题是我想验证"12500.00"之类的输入.格式应为小数点前的任何数字,小数点后为两位.例如:ddd.dd

我尝试了以下正则表达式.但是i不允许用户输入."特点.它允许用户输入除."外的任何数字.按下该键,输入不被接受.

这是我使用的正则表达式. "[[0-9] + | [0-9] +.| [0-9] +.[0-9] {1} | [0-9] +.[0-9] {2}"

重要:当用户输入到jtextfield时,逐个字符地验证用户输入.

这是代码

import java.awt.Toolkit;
import java.util.regex.Pattern;
import javax.swing.JComponent;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public abstract class ValidatedTextField extends PlainDocument {

private int max;
private String regExp;

public ValidatedTextField(int max, String regExp) {
    this.max = max;
    this.regExp = regExp;

}

@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
    Pattern DIGITS = Pattern.compile(regExp);
    // System.out.println(str);
    if (getLength() + str.length() > max) {
        str = str.substring(0, max - getLength());
        Toolkit.getDefaultToolkit().beep();
    }
    if (!DIGITS.matcher(str).matches() || str == null) {
        str = null;
        Toolkit.getDefaultToolkit().beep();
    }
    if (str != null && !passDependency(str)) {
        str = null;
        Toolkit.getDefaultToolkit().beep();
    }
    //str != null && DIGITS.matcher(str).matches

    super.insertString(offs, str, a);

}

public abstract boolean passDependency(String str);

public void shiftFocus(JComponent jc, boolean condition) {
    if (condition) {
        jc.requestFocusInWindow();
    }
}
}


下面不是确切的代码,但这是我的用法.

import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.*;

public class ValidateTest {
void makeFrame(){
    JFrame jf=new JFrame("Verifier Test");
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextField text = new JTextField();
    JLabel lbl=new JLabel("Price");

    text.setDocument(new ValidatedTextField(10, "[0-9]+") {

        @Override
        public boolean passDependency(String str) {
            return true;
        }
    });
    text.setPreferredSize(new Dimension(200, 30));
    lbl.setPreferredSize(new Dimension(60, 30));
    jf.getContentPane().add(text, BorderLayout.EAST);
    jf.getContentPane().add(lbl, BorderLayout.WEST);
    jf.pack();
    jf.setVisible(true);
    text.setVisible(true);
}
public static void main(String[] args) {
    new ValidateTest().makeFrame();
}
}

解决方案

您做得太多,而正则表达式并不总是解决方案.

使用带有amountFormat的JFormattedTextField

请参见 Sun的Java教程演示

I want to validate a jtextfield as user inputs a price of some item.

I have a perfectly working code which beeps and discard if user inputs some character that doesnt match the regular expression.(for regular expression "[0-9]+" it accepts any number of digits and beeps if a letter is given as input)

But the problem is I want to validate an input like "12500.00". Format should be any number of digits before decimal point and two digits after the decimal point. eg: ddd.dd

I tried the following regular expression. But the i doesnt allow user to input "." character. It allows user to input any number of digits but when "." key is pressed input is not accepted.

here is the regular expression I used. "[0-9]+ | [0-9]+. | [0-9]+.[0-9]{1} | [0-9]+.[0-9]{2}"

important: user input is validated character by character as the user inputs them to the jtextfield.

Here is the code

import java.awt.Toolkit;
import java.util.regex.Pattern;
import javax.swing.JComponent;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public abstract class ValidatedTextField extends PlainDocument {

private int max;
private String regExp;

public ValidatedTextField(int max, String regExp) {
    this.max = max;
    this.regExp = regExp;

}

@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
    Pattern DIGITS = Pattern.compile(regExp);
    // System.out.println(str);
    if (getLength() + str.length() > max) {
        str = str.substring(0, max - getLength());
        Toolkit.getDefaultToolkit().beep();
    }
    if (!DIGITS.matcher(str).matches() || str == null) {
        str = null;
        Toolkit.getDefaultToolkit().beep();
    }
    if (str != null && !passDependency(str)) {
        str = null;
        Toolkit.getDefaultToolkit().beep();
    }
    //str != null && DIGITS.matcher(str).matches

    super.insertString(offs, str, a);

}

public abstract boolean passDependency(String str);

public void shiftFocus(JComponent jc, boolean condition) {
    if (condition) {
        jc.requestFocusInWindow();
    }
}
}


Below is not the exact code but this is how I use it.

import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.*;

public class ValidateTest {
void makeFrame(){
    JFrame jf=new JFrame("Verifier Test");
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextField text = new JTextField();
    JLabel lbl=new JLabel("Price");

    text.setDocument(new ValidatedTextField(10, "[0-9]+") {

        @Override
        public boolean passDependency(String str) {
            return true;
        }
    });
    text.setPreferredSize(new Dimension(200, 30));
    lbl.setPreferredSize(new Dimension(60, 30));
    jf.getContentPane().add(text, BorderLayout.EAST);
    jf.getContentPane().add(lbl, BorderLayout.WEST);
    jf.pack();
    jf.setVisible(true);
    text.setVisible(true);
}
public static void main(String[] args) {
    new ValidateTest().makeFrame();
}
}

解决方案

You are doing too much and a regex is not always the solution.

Use a JFormattedTextField with the amountFormat

See Sun's Java tutorial and demo

这篇关于在jtextfield中评估“价格"的正则表达式是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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