[ Back | Previous | Next ]

How to use PlainDocument for inputmasking?

Package:
javax.swing.text.*
Product:
Swing
Release:
1.0.x
Related Links:
General
JEditorPane
PlainDocument
Comment:
	getJTextField111().setDocument(new PlainDocument() {
		public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
			String acceptedChars = "0123456789";
			int fieldLength = 2;
			if (str == null)
				return;
			if (offset >= fieldLength) {
				return;
			}
			// does the insertion exceed the max length
			if (str.length() > fieldLength) {
				str = str.substring(0, fieldLength);
			}
			if (acceptedChars == null) {
				System.out.println("No filter selected.");
				super.insertString(offset, str, attr);
				return;
			}
			for (int i = 0; i < str.length(); i++) {
				if (acceptedChars.indexOf(str.valueOf(str.charAt(i))) == -1)
					return;
			}
			super.insertString(offset, str, attr);
		}
	});
1