Changing Document contents during insertUpdate
Hi All,
I have the following problem.
I have JTextField and I want to make sure only numbers can be typed there. In JFormattedTextField therotically it is possible but only when the component losses focus. And I want to do that instantly (as the user is still typing).
I have tried DocumentListener:
publicvoid insertUpdate(DocumentEvent e){
try{
Document doc = e.getDocument();
int len = doc.getLength();
String cont = doc.getText(len-1,1);
try{
Integer.valueOf(cont);
}catch (NumberFormatException nfe){
doc.remove(len-1,1);
}
}catch (BadLocationException ble){
ble.printStackTrace();
System.exit(1);
}
}
but this throws IllegalStateException (the document cannot be modified inside DocumentListener).
I have tried KeyListener:
publicvoid keyTyped(KeyEvent e){
if (wField.getText().length()==0)
return;
try{
Integer.valueOf(wField.getText().substring(wField.getText().length()-1));
}catch (NumberFormatException nfe){
wField.setText(wField.getText().substring(0,wField.getText().length()-1));
}
}
but this get executed before character is placed into text field, and the change is made when I press another key.
Any one has any ideas?
# 1
> In JFormattedTextField therotically it is possible but only when the component losses focus.
Not theoritcallyl possible, it is possible and it has nothing to do with the Component losing focus. You use a MaskFormatter.
Otherwise you should be using a [url http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#filter]DocumentFilter[/url], not a DocumentListener.
# 2
OK. I am trying DocumentFilter. I have written a class:
class DocumentNumberFilter extends DocumentFilter{
public void insertString(FilterBypass fb, int offs,
String str, AttributeSet a)
throws BadLocationException {
System.out.println(str);
}
}
just to see what is fed into filter. And added:
((AbstractDocument)wField.getDocument()).setDocumentFilter(new DocumentNumberFilter());
to my code but I don't see anything output to console. What am I doing wrong?
# 3
Are you adding the DocumentFilter to the
a) JTextField (in which case it should work) or,
b) a JFormattedTextField( in which case I don't think it will work since a formatted text field uses its own custom DocumentFilter, I believe. Also its not necessary, you just use the MaskFormatter).
Copy the working example from the tutorial and test it.
# 4
JTextField does not have method setDocumentFilter(DocumentFilter). (In 1.5. Does it in 1.6)
This is from tutorials:
StyledDocument styledDoc = textPane.getStyledDocument();
if (styledDoc instanceof AbstractDocument) {
doc = (AbstractDocument)styledDoc;
doc.setDocumentFilter(new DocumentSizeFilter(MAX_CHARACTERS));
}
I've been there as soon as you told me about DocumentFilter. :)
Looks the same (almost) in my code but does not work.