I was trying to create an applet with a TextField that would only accept an integer, and ignore any other keystrokes. Eg, if a user typed in an 'f' into the field, the TextField should ignore it, and not even put the f into the textbox.
However, the TextField does not appear to update until one keypress after I need it to. Eg. if I typed, 10fg, it would end up as "10f" then after the g, become "g10".
I'm currently using the keyPressed Event
The TextField is named delayTime
The stored integer is named delayInt
-
public void keyPressed(KeyEvent keyEvent) {
-
-
String delayStr = delayTime.getText();
-
char keyChar = keyEvent.getKeyChar();
-
//System.out.println("Key pressed:"+keyChar);
-
try{
-
if (delayStr.equals("")){
-
delayInt = 0;
-
} else {
-
int i;
-
i = Integer.parseInt(delayStr);
-
delayInt = i;
-
}
-
}catch(Exception e){
-
delayTime.setText((new Integer(delayInt)).toString());
-
}
-
}
-
Is there a better way to restrict the text in a textfield? My current code does not appear to be doing it. A different event perhaps?
Link used http://java.sun.com/docs/books/tutor...ylistener.html
The difference between keypressed and keyreleased is that, the keyevent triggered by keypressed is then first to execute before the character appear at the text field... And the keyevent in keyreleased is then be executed after the character is printed to the textfield,
You can not really see the character printed if you use the keypressed when you entered it and following the said event...(if you want to erase it)
Another way to ignore any non-integer,
Algo...
(Trigger this in keyreleased event)...
Every input that the user do, copy first the old text (Before the user input again or at the start)inside the textfield in a
temp variable,
Test if the last character in the
new text is not a non-integer...
If the last character is non-integer, then simply retrieve the value you have stored from the
tempvariable
if satisfied, then allow...
For me, it is safe to implement this, how about your new idea?
Concerned,
Sukatoa(Shadow shaman)