【问题标题】:how to validate a jtextfield to accept only integer numbers [duplicate]如何验证 jtextfield 只接受整数 [重复]
【发布时间】:2012-12-28 10:47:14
【问题描述】:

可能重复:
Restricting JTextField input to Integers
Detecting JTextField “deselect” event

我需要验证JTextField,如果用户输入除数字以外的任何字符,则允许用户在其中输入整数值.我已将其编码为数字值,但我还需要丢弃字母

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

【问题讨论】:

标签: java swing


【解决方案1】:

除了使用 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 的构造函数。

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      使用JFormattedTextField 功能。看看example

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-12-22
        • 1970-01-01
        • 1970-01-01
        • 2017-09-14
        • 1970-01-01
        • 2016-01-13
        • 2016-03-26
        相关资源
        最近更新 更多