Results 1 to 4 of 4
  1. #1
    tomtraxler is offline Member
    Join Date
    Jan 2011
    Posts
    2
    Rep Power
    0

    Default Nullifying Keypress or KeyTyped Event

    I want to test input in a textfield using KeyPress or KeyTyped (or any Key Event) and have the application not accept the keystroke (or make it do nothing) if the character typed is not a numeral. Can anyone tell me how to do that? I do not want to test the input after it has been typed in. I can do that. I want to prevent the character from even showing up if it is not a numeral.

    I need to figure how to complete this---or use an alternate method:

    private void ValidateChildrenInput(java.awt.event.KeyEvent evt) {
    int keyCode=evt.getKeyCode(); //assigns the keypress variable
    if ( (keyCode<48 | keyCode>57) {

    //I NEED THE CODE HERE TO CANCEL THE CHARACTER TYPED }
    else
    return ;
    }

  2. #2
    Iron Lion is offline Senior Member
    Join Date
    Nov 2010
    Posts
    210
    Rep Power
    4

    Default

    Maybe you could use the getText() and setText() methods of JTextField, as well as String.substring(), to revert the text to what it was before the character was typed? Not sure if there's a more elegant solution than that.

  3. #3
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,447
    Blog Entries
    7
    Rep Power
    20

    Default

    Wouldn't a JFormattedTextField do the job? Read the API documentation of that class (there are examples in there).

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    If the JFormattedTextField idea doesn't work, then perhaps a DocumentFilter can do the trick. Check out the Java Swing tutorials on this as well as examples of these in this forum.

Similar Threads

  1. Identifying sender on keypress event
    By tomtraxler in forum NetBeans
    Replies: 1
    Last Post: 01-08-2011, 04:49 PM
  2. About focusLost and keyTyped, need feedback
    By mine0926 in forum NetBeans
    Replies: 0
    Last Post: 06-26-2010, 10:08 AM
  3. Java keypress detection help
    By pghazanfari in forum Advanced Java
    Replies: 1
    Last Post: 05-29-2010, 08:30 PM
  4. KeyPress for my Button
    By bigj in forum New To Java
    Replies: 3
    Last Post: 01-26-2010, 04:27 PM
  5. Char comparison/assigning through keyTyped
    By AdamMurg in forum Java Applets
    Replies: 0
    Last Post: 10-21-2009, 05:42 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •