jTextField验证数字和一个小数点?

时间:2013-01-08 13:18:41

标签: java swing validation decimal jtextfield

我需要设置一个jTextField只接受数字和一个小数点。没有别的。小数点不能多次输入,也不允许其他字符。我怎么能这样做?

我输入了这段代码。但它效果不好。我的意思是它接受字符串直到我输入小数点

    if (!Character.isDigit(evt.getKeyChar()) & crqty.getText().indexOf(".") != -1) {
        evt.consume();
    }

5 个答案:

答案 0 :(得分:4)

您似乎正在使用KeyListener来管理KeyEvents in the JTextField。这不适合过滤此JTextComponent的文档。在这里,您可以使用JFormattedTextFieldMaskFormatter相结合来接受以小数点分隔的最多8位数字。

JFormattedTextField textField = new JFormattedTextField();
MaskFormatter dateMask = new MaskFormatter("####.####");
dateMask.install(textField);

对于更自由格式的输入(例如更多数字),您可以使用DocumentFilterJTextField。这是一个整数过滤器example

答案 1 :(得分:3)

非常好的问题!我很久以前下载了这段代码(我不记得它是哪个网站),只允许你输入一个数字:

import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.text.*;

public class JNumericField extends JTextField {
    private static final long serialVersionUID = 1L;

    private static final char DOT = '.';
    private static final char NEGATIVE = '-';
    private static final String BLANK = "";
    private static final int DEF_PRECISION = 2;

    public static final int NUMERIC = 2;
    public static final int DECIMAL = 3;

    public static final String FM_NUMERIC = "0123456789";
    public static final String FM_DECIMAL = FM_NUMERIC + DOT; 

    private int maxLength = 0;
    private int format = NUMERIC;
    private String negativeChars = BLANK;
    private String allowedChars = null;
    private boolean allowNegative = false;
    private int precision = 0;

    protected PlainDocument numberFieldFilter;

    public JNumericField() {

        this(2, DECIMAL);
    }

    public JNumericField(int iMaxLen) {
        this(iMaxLen, NUMERIC);
    }

    public JNumericField(int iMaxLen, int iFormat) {
        setAllowNegative(true);
        setMaxLength(iMaxLen);
        setFormat(iFormat);

        numberFieldFilter = new JNumberFieldFilter();
        super.setDocument(numberFieldFilter);
    }

    public void setMaxLength(int maxLen) {
        if (maxLen > 0)
            maxLength = maxLen;
        else
            maxLength = 0;
    }

    public int getMaxLength() {
        return maxLength;
    }

    public void setEnabled(boolean enable) {
        super.setEnabled(enable);

        if (enable) {
            setBackground(Color.white);
            setForeground(Color.black);
        } else {
            setBackground(Color.lightGray);
            setForeground(Color.darkGray);
        }
    }

    public void setEditable(boolean enable) {
        super.setEditable(enable);

        if (enable) {
            setBackground(Color.white);
            setForeground(Color.black);
        } else {
            setBackground(Color.lightGray);
            setForeground(Color.darkGray);
        }
    }

    public void setPrecision(int iPrecision) {
        if (format == NUMERIC)
            return;

        if (iPrecision >= 0)
            precision = iPrecision;
        else
            precision = DEF_PRECISION;
    }

    public int getPrecision() {
        return precision;
    }

    public Number getNumber() {
        Number number = null;
        if (format == NUMERIC)
            number = new Integer(getText());
        else
            number = new Double(getText());

        return number;
    }

    public void setNumber(Number value) {
        setText(String.valueOf(value));
    }

    public int getInt() {
        return Integer.parseInt(getText());
    }

    public void setInt(int value) {
        setText(String.valueOf(value));
    }

    public float getFloat() {
        return (new Float(getText())).floatValue();
    }

    public void setFloat(float value) {
        setText(String.valueOf(value));
    }

    public double getDouble() {
        return (new Double(getText())).doubleValue();
    }

    public void setDouble(double value) {
        setText(String.valueOf(value));
    }

    public int getFormat() {
        return format;
    }

    public void setFormat(int iFormat) {
        switch (iFormat) {
        case NUMERIC:
        default:
            format = NUMERIC;
            precision = 0;
            allowedChars = FM_NUMERIC;
            break;

        case DECIMAL:
            format = DECIMAL;
            precision = DEF_PRECISION;
            allowedChars = FM_DECIMAL;
            break;
        }
    }

    public void setAllowNegative(boolean b) {
        allowNegative = b;

        if (b)
            negativeChars = "" + NEGATIVE;
        else
            negativeChars = BLANK;
    }

    public boolean isAllowNegative() {
        return allowNegative;
    }

    public void setDocument(Document document) {
    }

    class JNumberFieldFilter extends PlainDocument {
        private static final long serialVersionUID = 1L;

        public JNumberFieldFilter() {
            super();
        }

        public void insertString(int offset, String str, AttributeSet attr)
                throws BadLocationException {
            String text = getText(0, offset) + str
                    + getText(offset, (getLength() - offset));

            if (str == null || text == null)
                return;

            for (int i = 0; i < str.length(); i++) {
                if ((allowedChars + negativeChars).indexOf(str.charAt(i)) == -1)
                    return;
            }

            int precisionLength = 0, dotLength = 0, minusLength = 0;
            int textLength = text.length();

            try {
                if (format == NUMERIC) {
                    if (!((text.equals(negativeChars)) && (text.length() == 1)))
                        new Long(text);
                } else if (format == DECIMAL) {
                    if (!((text.equals(negativeChars)) && (text.length() == 1))) 
                        new Double(text);

                    int dotIndex = text.indexOf(DOT);
                    if (dotIndex != -1) {
                        dotLength = 1;
                        precisionLength = textLength - dotIndex - dotLength;

                        if (precisionLength > precision)
                            return;
                    }
                }
            } catch (Exception ex) {
                return;
            }

            if (text.startsWith("" + NEGATIVE)) {
                if (!allowNegative)
                    return;
                else
                    minusLength = 1;
            }

            if (maxLength < (textLength - dotLength - precisionLength - minusLength))
                return;

            super.insertString(offset, str, attr);
        }
    }
}

您将以这种方式使用它:

JNumericField numField = new JNumericField();

numField.setMaxLength(10); //Set maximum length             
numField.setPrecision(1); //Set precision (1 in your case)              
numField.setAllowNegative(true); //Set false to disable negatives

答案 2 :(得分:0)

您可以对JTextField进行简单验证....

JTextField.addKeyListener(new java.awt.event.KeyAdapter() {
  public void keyTyped(java.awt.event.KeyEvent evt) {

    char text[];
        int count = 0; 
        text = JTextField.getText().toCharArray();
        for(int i = 0 ; i< text.length ; i++){
            if(text[i] == '.'){
                count++;
            }
        }
        if(count>=1 && evt.getKeyChar() == '.'){
            evt.consume();
        }

  }
});

答案 3 :(得分:0)

   if(!Character.isDigit(evt.getKeyChar())&&evt.getKeyChar()!='.'){
       evt.consume();
   } 
   if(evt.getKeyChar()=='.'&&jTextField1.getText().contains(".")){
      evt.consume();
       }   

答案 4 :(得分:-1)

char c=evt.getKeyChar();
if(!(Character.isDigit(c)||
    (c==KeyEvent.VK_BACK_SPACE)||c==KeyEvent.VK_DELETE||evt.getKeyChar() == '.')){
//  evt.getKeyChar() == '.' does accept point when jtextfield accepts decimal number
  evt.consume();
  getToolkit().beep();
}