how to make jtextfield only accept characters in netbeans

纵饮孤独 提交于 2019-12-18 09:38:06

问题


I have done a sample project in netbeans of registration. In the jtextfield1 is the user id and Jtextfiled7 is country, Both must in characters not in numeric or not allowed spaces and special characters.how it is possible?


回答1:


@Vivek ,

I have the answer for this question you asked. please do as per following instructions.

In Netbeans right click on JTextfield and select the events>>key>>key typed and enter the following code between the codes. the following is the code for it for only accept characters

enter code here
char c=evt.getKeyChar();

    if(!(Character.isAlphabetic(c) ||  (c==KeyEvent.VK_BACKSPACE)||  c==KeyEvent.VK_DELETE ))
        evt.consume();



回答2:


You can use JFormattedTextField or you can code inside the JTextField's KeyTyped event

jTextField.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyTyped(java.awt.event.KeyEvent evt) {

         if(!(Character.isLetter(evt.getKeyChar()))){
                evt.consume();
            }
        }
    });



回答3:


For real time validation, use a DocumentFilter, see and Implementing a Document Filter and DocumentFilter Examples for more details.

Have a look at:

  • JTextField limiting character amount input and accepting numeric only
  • How to set DocumentFilter with input length and range? e.g. 1-3 or 10-80

for more examples.

For post validation, see Validating Input for more details



来源:https://stackoverflow.com/questions/34377607/how-to-make-jtextfield-only-accept-characters-in-netbeans

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!