Re: Keystroke validation in JTextField
icogs wrote:
Simple one I hope:
How can I intercept keystrokes to a JTextField so I could, for
example, implement a digit-only text field.
You don't want to do it that way with JComponents. Use a Document to
control those sorts of things. Look at PlainDocument in the docs and
see an example below of how to implement a document that only allows
upper case letters.
//
//
// UpperCaseDocument
//
//
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class UpperCaseDocument extends PlainDocument {
int length = 0;
public UpperCaseDocument() {
}
public UpperCaseDocument(int length) {
this.length = length;
}
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if (str == null) {
return;
}
if (length > 0)
if (str.length() + getLength() > length)
str = str.substring(0,length - getLength());
char[] upper = str.toCharArray();
for (int i = 0; i < upper.length; i++)
upper[i] = Character.toUpperCase(upper[i]);
super.insertString(offs, new String(upper), a);
}
}
--
Knute Johnson
email s/nospam/knute/