swing 文本框输入内容限制

目录:

  • 源码
  • 效果图

java源码:

package textfield;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

import org.apache.commons.lang.ArrayUtils;

public class AllowInputChar extends JFrame{
	private JTextField field;
	public AllowInputChar() {
		setLayout(new BorderLayout());
		setTitle("Allow input char");
	    field = new JTextField();
		add(field);
		
		field.setDocument(new InputCharFilter());
		
		diplay();
	}
	
	private void diplay() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(new Dimension(300,100));
		setVisible(true);
	}
	
	public static void main(String[] args) {
		new AllowInputChar();
	}
	
	public class InputCharFilter extends PlainDocument{
		public  final char[] FIRST_CHARS = {'0'};
		public  final char[] ALLOW_CHARS = {'0','1','2','3','4','5','6','7','8','9'};
		
		@Override
		public void insertString(int offs, String str, AttributeSet a)
				throws BadLocationException {
			
			//首字母不能为0
			if(getLength()==0){
				if(ArrayUtils.contains(FIRST_CHARS, str.charAt(0))){
					return;
				}
			}
			//必须为纯数字
			if(!ArrayUtils.contains(ALLOW_CHARS, str.charAt(0))){
				return;
			}
			
			super.insertString(offs, str, a);
		}
		
	}
	
}
效果图:


阅读更多
文章标签: Swing
个人分类: Swing
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭