2

可能重复:
将 JTextField 输入限制为整数
检测 JTextField “取消选择”事件

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)");
    }
}
4

3 回答 3

6

除了使用 JFormattedTextField,您可以编写一个自定义 JTextField,其中包含仅允许整数的文档。我只喜欢更复杂的掩码的格式化字段......看看。

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,您只需将常规 JTextFields 放入您的 GUI 和创建代码中,您将指定 IntegerField 的构造函数。

于 2013-01-14T13:17:04.343 回答
1

有一个组件:格式化文本字段: http ://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html

于 2013-01-14T13:16:35.577 回答
1

使用JFormattedTextField能力。看看例子

于 2013-01-14T13:16:46.193 回答