ludc
2023-09-19 8381325223bee254168855b1b697db31fc591b9e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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("-?");
}