I have a custom text field that only accepts numbers in it.
Everything works fine except when I try to handle the negative (-) sign.
public void processKeyEvent(KeyEvent ev) {
char c = ev.getKeyChar();
[...]
if(c == '-' && getDocument().getLength() > 0 ){
ev.consume();
}else{
super.processKeyEvent(ev);
}
}
This works fine when I start with the sign – but not when I already have numbers and want to add a - in front.
What I really need is a way to get the position at which this character is inserted but I can’t find that.
Any ideas?
You can get the current position inside a text field via the method
JTextComponent.getCaretPosition().It might be easier to fulfill this task with either a
DocumentListeneror anInputVerifieron your text component.