Swing入力检查

/**
 * JTextField input Check
 * 
 * @author shuai.zhang
 */
public class InputCheck extends KeyAdapter {

	/**
	 * check is none.
	 */
	public static final int NONE = 0;

	/**
	 * number check.
	 */
	public static final int NUMBER = 1;

	/**
	 * half char check.
	 */
	public static final int HALF = 2;

	/**
	 * all char check.
	 */
	public static final int ALL = 3;

	/**
	 * UID
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * input length.
	 */
	private int length = 0;

	/**
	 * about the input type.
	 */
	private int _judgeType = NONE;

	/**
	 * JTextField
	 */
	private JTextField jTextField = null;

	/**
	 * 
	 * @param jTextField
	 *            JTextField
	 * @param length
	 *            input length.
	 * @param judgeType
	 *            check type.
	 */
	public InputCheck(JTextField jTextField, int length, int judgeType) {
		this.jTextField = jTextField;
		this.length = length;
		this._judgeType = judgeType;
	}

	/**
	 * action.
	 * 
	 * @param e
	 *            event.
	 */
	public void keyTyped(KeyEvent e) {

		String input = String.valueOf(e.getKeyChar());
		boolean flag = false;
		// first check length.
		flag = lengthJudge(
				length,
				(jTextField.getText().getBytes().length + input.getBytes().length));

		switch (_judgeType) {
		case NONE:
			// about none.
			break;
		case NUMBER:
			// about number.
			flag = flag && input.matches("\\d");
			break;
		case HALF:
			// about half char.
			flag = (flag && (input.getBytes().length == 1 ? true : false));
			break;
		case ALL:
			// about all char.
			flag = (flag && (input.getBytes().length == 1 ? false : true));
			break;
		}

		if (!flag) {
			e.consume();
		}
	}

	/**
	 * length check.
	 * 
	 * @param formatLength
	 *            set length
	 * @param inputLength
	 *            input length
	 */
	private boolean lengthJudge(int formatLength, int inputLength) {
		return formatLength >= inputLength ? true : false;
	}

}

你可能感兴趣的:(swing)