Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2500126
  • 博文数量: 319
  • 博客积分: 9650
  • 博客等级: 中将
  • 技术积分: 3881
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-27 21:05
文章分类

全部博文(319)

文章存档

2017年(5)

2016年(10)

2015年(3)

2014年(3)

2013年(10)

2012年(26)

2011年(67)

2010年(186)

2009年(9)

分类: Java

2010-03-04 11:03:44

此类可实现文本框只接收数字键及小数点(只允许输入一次小数点)功能。
并且防止用户粘贴非法数字。
 
import java.awt.Toolkit;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
/**
 *
 * @author Administrator
 */
//注:此类没有检查负号,即不能输入负数,使用下面的正则表达式则可优雅地处理各种情况
//方法1:
public class DecimalOnlyDocument extends PlainDocument {
    private boolean dot = false;//true:已经有小数点  0:还没有小数点
    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        if ((super.getText(0, super.getLength())).indexOf('.') == -1) {//检查原来文本框是否已经有小数点
            dot = false;
        } else {
            dot = true;
        }
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) < '0' || str.charAt(i) > '9') {
                if (str.charAt(i) != '.' || dot) {
                    Toolkit.getDefaultToolkit().beep();//蜂鸣器响一声
                    return;//非小数点的字母或者已经有小数点,返回
                }
                else
                    dot = true;
            }
        }
        /*if (str.indexOf('.') != -1)
        dot = true;*/
        super.insertString(offs, str, a);
    }
}
 
//方法2:使用正则表达式则可优雅地处理[推荐]
import java.awt.Toolkit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class DecimalOnlyDocument extends PlainDocument {
    private boolean dot = false;//true:已经有小数点  0:还没有小数点
    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        StringBuffer tmp = new StringBuffer(super.getText(0, super.getLength()));
        tmp.insert(offs, str);
        Pattern p = Pattern.compile("^-?\\d*(");
        Matcher m = p.matcher(tmp.toString());
        if (m.find()) {
            super.insertString(offs, str, a);
        }
 else
            Toolkit.getDefaultToolkit().beep();//蜂鸣器响一声
    }
}
  使用:     
        JTextField num1 = new JTextField(10);
        num1.setDocument(new NumOnly());

    
   
阅读(5305) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~