-2

So I have a textfield which I want to be max length 10 and only letters, this is what I've came up with:

private void textField1KeyTyped(java.awt.event.KeyEvent evt) {                                      
    
    char c= evt.getKeyChar();
    if( !(Character.isAlphabetic(c)) ){
        evt.consume();   
    }
    if ((textField1.getText().length()) > 10){
        evt.consume();
    }  
}  

It kind of works but I've seen some tutorials that use something like this:

private void textField1KeyTyped(java.awt.event.KeyEvent evt) {                                      
    
    char c= evt.getKeyChar();
    if( (Character.isAlphabetic(c)) ){
        if((textField1.getText().length()) <= 10){
            textField1.setEditable(true);
        }else {
            textField1.setEditable(false);
        } 
    }else {
        if( (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE) ){
            textField1.setEditable(true);
        }else {
            textField1.setEditable(false);
        }
    }
 } 

Which one is right?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • 1
    Is this a Swing GUI? If so, then neither is correct, and the best solution would be to add a DocumentFilter to the text field's Document. Please review MadProgrammer's answer [here](https://stackoverflow.com/a/24473097/522444). – Hovercraft Full Of Eels Nov 14 '22 at 07:23

1 Answers1

0

Both will stop the text-field from consuming further keys.

  1. calling InputEvent.consume() marks the event as consumed, so that the textfield will not consume it and add the key to it's contents. See What does e.consume() do in java
  2. disabling editing on the textfield with setEditable(false) will also prevent the textfield from editing, that is consuming the key. But it also makes this behaviour, the lock, visible to the user.
hc_dev
  • 8,389
  • 1
  • 26
  • 38