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();
开发者_StackOverflow [...]
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 DocumentListener
or an InputVerifier
on your text component.
If your control is a TextComponent
or derived from that, you could try using the getCaretPosition
method to check whether or not the input is being typed at the start of the text.
精彩评论