JTextField限制输入数字的方法

// 第一种,扩展关联文本
final JTextField txtExamTotal = new JTextField();
// 3位数字
txtExamTotal.setDocument(new NumberValidator(3));

// 扩展类

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

/**
 * 数字,位数限制
 * 
 * @author 邓杰
 */
public class NumberValidator extends PlainDocument {

	private static final long serialVersionUID = 1L;

	private int limit;

	public NumberValidator(int limit) {
		super();
		this.limit = limit;
	}

	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;
			for (int i = 0; i < upper.length; i++) {
				if (upper[i] >= '0' && upper[i] <= '9') {
					upper[length++] = upper[i];
				}
			}
			// 插入数字
			super.insertString(offset, new String(upper, 0, length), attr);
		}
	}

}

// 第二种,通过keyTyped方法过滤
final JTextField txtExamTotal = new JTextField();
txtExamTotal.addKeyListener(new KeyListener() {
	@Override
	public void keyTyped(KeyEvent e) {
		// 只能输入数字
		char keyCh = e.getKeyChar();
		if ((keyCh < '0') || (keyCh > '9')) {
			if (keyCh != '') // 回车字符
				e.setKeyChar('\0');
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
	}

	@Override
	public void keyPressed(KeyEvent e) {
	}
});
 
 

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