package com.vci.rmip.code.client.codeapply.Apply410.swing;
|
|
import java.io.Serializable;
|
import java.util.LinkedList;
|
import java.util.regex.Pattern;
|
|
import javax.swing.text.AttributeSet;
|
import javax.swing.text.BadLocationException;
|
import javax.swing.text.PlainDocument;
|
|
/**
|
*
|
* @author xiongchao
|
*
|
*/
|
public class NumberPlainDocument extends PlainDocument implements Serializable {
|
|
/**
|
*
|
*/
|
private static final long serialVersionUID = 3552883300862479018L;
|
/**
|
*
|
*/
|
|
boolean floatFlag = false;
|
public NumberPlainDocument(boolean floatFlag){
|
this.floatFlag = floatFlag;
|
}
|
|
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
|
if (str == null) {
|
return;
|
}
|
char[] chars = str.toCharArray();
|
LinkedList<Character> charsList = new LinkedList<Character>();
|
for(char c : chars){
|
// -号要么出现,且只能在最前面,要到不出现
|
if(offs != 0 && pMinus.matcher(String.valueOf(c)).matches()){
|
continue;
|
}
|
// 匹配数字
|
if(pNum.matcher(String.valueOf(c)).matches()){
|
charsList.add(c);
|
}
|
// 匹配减号
|
else if(pMinus.matcher(String.valueOf(c)).matches()){
|
charsList.add(c);
|
}
|
else if(String.valueOf(c).equals(".")){
|
if(floatFlag){
|
charsList.add(c);
|
}
|
}
|
}
|
char[] charsNew = new char[charsList.size()];
|
for(int i = 0; i < charsNew.length; i++){
|
charsNew[i] = charsList.get(i);
|
}
|
super.insertString(offs, new String(charsNew), a);
|
}
|
|
private Pattern pNum = Pattern.compile("\\d+");
|
private Pattern pMinus = Pattern.compile("-?");
|
}
|