如何验证jtextfield只接受整数 [英] how to validate a jtextfield to accept only integer numbers
问题描述
我需要验证 JTextField
允许用户只输入整数值,如果用户输入除数字以外的任何字符,则应显示 JOptionPane.show
消息框,显示该值输入不正确,只允许整数。我已将其编码为数字值,但我还需要丢弃字母
i need to validate a JTextField
by allowing the user to input only integer values in it if user enters any char other than numbers a JOptionPane.show
messagebox should appear showing that the value entered are incorrect and only integer numbers are allowed. I have coded it for a digit values but i also need to discard the alphabets
public void keyPressed(KeyEvent EVT) {
String value = text.getText();
int l = value.length();
if (EVT.getKeyChar() >= '0' && EVT.getKeyChar() <= '9') {
text.setEditable(true);
label.setText("");
} else {
text.setEditable(false);
label.setText("* Enter only numeric digits(0-9)");
}
}
推荐答案
使用JFormattedTextField,您可以使用仅允许整数的文档编写自定义JTextField。我喜欢格式化的字段只用于更复杂的掩码...
看看。
Instead of using a JFormattedTextField, you may write a custom JTextField with a document that allows only integers. I like formatted fields only for more complex masks... Take a look.
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
/**
* A JTextField that accepts only integers.
*
* @author David Buzatto
*/
public class IntegerField extends JTextField {
public IntegerField() {
super();
}
public IntegerField( int cols ) {
super( cols );
}
@Override
protected Document createDefaultModel() {
return new UpperCaseDocument();
}
static class UpperCaseDocument extends PlainDocument {
@Override
public void insertString( int offs, String str, AttributeSet a )
throws BadLocationException {
if ( str == null ) {
return;
}
char[] chars = str.toCharArray();
boolean ok = true;
for ( int i = 0; i < chars.length; i++ ) {
try {
Integer.parseInt( String.valueOf( chars[i] ) );
} catch ( NumberFormatException exc ) {
ok = false;
break;
}
}
if ( ok )
super.insertString( offs, new String( chars ), a );
}
}
}
<如果您使用NetBeans构建GUI,只需要在GUI和创建代码中放置常规JTextField,就可以指定IntegerField的构造函数。
If you are using NetBeans to build your GUI, you just need to put regular JTextFields in your GUI and in the creation code, you will specify the constructor of IntegerField.
这篇关于如何验证jtextfield只接受整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!