JTextField设置输入指定长度的指定字符

JTextField设置输入指定长度的指定字符

范围参数是可变

TextField.setDocument(new Validator(2,"A-Z","a-z"));
package com.wxn.tempbom.create;

import javax.swing.text.AttributeSet;
import javax.swing.text.PlainDocument;

/**
 * 数字,位数限制
 * 
 * @author chen
 */
public class Validator extends PlainDocument {
 
	private static final long serialVersionUID = 1L;
 
	private int limit;

	private String[] arr;
 
	
	public Validator(int limit,String... arr) {
		super();
		this.limit = limit;
		this.arr = arr;
	}
 
	public void insertString(int offset, String str, AttributeSet attr)
			throws javax.swing.text.BadLocationException {
		if (str == null) {
			return;
		}
		if ((getLength() + str.length()) <= limit) {
			
				
			char[] upper = str.toCharArray();
			int length = 0;
			out:for (int i = 0; i < upper.length; i++) {
				for (int j = 0; j < arr.length; j++) {
					if (upper[i] >= arr[j].charAt(0) && upper[i] <= arr[j].charAt(2)) {
						upper[length++] = upper[i];
						break out;
					}
				}
			}
			// 插入数字
			super.insertString(offset, new String(upper, 0, length), attr);
		}
	}
 
}

你可能感兴趣的:(java,SE)