我需要JTextField通过允许用户仅输入整数值来验证a ,如果用户输入除数字以外的任何字符,JOptionPane.show则应显示消息框,表明输入的值不正确且仅允许整数.我已将其编码为数字值,但我还需要丢弃字母
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)");
    }
}
您可以使用仅允许整数的文档编写自定义JTextField,而不是使用JFormattedTextField.我喜欢格式化的字段只用于更复杂的掩码......看一看.
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的构造函数.
| 归档时间: | 
 | 
| 查看次数: | 47442 次 | 
| 最近记录: |