0

I'm trying to make a jTextField in NetBeans that accepts letters ONLY. So far, I'v managed to make it so using the KeyTyped event. However, if the user CTRL+C any text, the jTextField will accept that text when CTRL+V'd. I want to prevent that.

Here is the event code:

private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {                                     
    // TODO add your handling code here:
    char c=evt.getKeyChar();

    if(!(Character.isAlphabetic(c)) &&  !(c==KeyEvent.VK_SPACE) ){
        evt.consume();
    }
}

Example

Lestat
  • 71
  • 2
  • 9
  • 1
    You don't need to take care of this sort of thing through the JTextField events. What you need to do is create and use a [**DocumentFilter**](https://docs.oracle.com/javase/7/docs/api/javax/swing/text/DocumentFilter.html) for your specific JTextField. [See This SO Answer](https://stackoverflow.com/a/14060047/4725875) which provides a good example. Apply the filter to whatever JTextFields you like. – DevilsHnd - 退職した Oct 26 '18 at 05:50
  • It worked! Thank you! – Lestat Oct 27 '18 at 00:06
  • Also note that you can dynamically turn ON the filter with: `((AbstractDocument) jTextField1.getDocument()).setDocumentFilter(new MyDocumentFilter());` and dynamically turn OFF the filter with: `((AbstractDocument) jTextField1.getDocument()).setDocumentFilter(null);`. – DevilsHnd - 退職した Oct 27 '18 at 00:11

0 Answers0