java 如何使 jtextfield 只接受 netbeans 中的字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34377607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to make jtextfield only accept characters in netbeans
提问by Vivek
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?
我在注册的 netbeans 中做了一个示例项目。在 jtextfield1 中是用户 ID,Jtextfiled7 中是国家,两者都必须是非数字字符或不允许的空格和特殊字符。这怎么可能?
回答by Lahiru Jayathilake
You can use JFormattedTextField or you can code inside the JTextField's KeyTyped event
您可以使用 JFormattedTextField 或者您可以在 JTextField 的 KeyTyped 事件中编写代码
jTextField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
if(!(Character.isLetter(evt.getKeyChar()))){
evt.consume();
}
}
});
回答by MadProgrammer
For real time validation, use a DocumentFilter
, see and Implementing a Document Filterand DocumentFilter Examplesfor more details.
对于实时验证,请使用DocumentFilter
,查看和实现文档过滤器和文档过滤器示例以获取更多详细信息。
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 Inputfor more details
对于后验证,请参阅验证输入以获取更多详细信息
回答by MadProgrammer
@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
在 Netbeans 中,右键单击 JTextfield 并选择 events>>key>>key typed 并在代码之间输入以下代码。以下是仅接受字符的代码
enter code here
char c=evt.getKeyChar();
if(!(Character.isAlphabetic(c) || (c==KeyEvent.VK_BACKSPACE)|| c==KeyEvent.VK_DELETE ))
evt.consume();