JTextField只接受有效的未签名短裤吗? (使用KeyAdapter) [英] JTextField accept only valid unsigned Shorts? (Using KeyAdapter)

查看:88
本文介绍了JTextField只接受有效的未签名短裤吗? (使用KeyAdapter)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我试图使KeyAdapter只接受小于65535的值的KeyAdapter.似乎它在实际位置后面落后了一个按键.例如,如果我键入"55",则System.out.println将产生"5",执行"3298"将产生"329",等等.

Below is the KeyAdapter I tried to get working to only accept values less than 65535. It seems as though it gets it one keystroke behind where it actually should. For example, If I type "55", the System.out.println will yield "5", doing "3298" will yield "329", etc.

// Allows for unsigned short values only
KeyAdapter unsignedShortAdapter = new KeyAdapter() {

    public void keyTyped(KeyEvent e) {
        char c = e.getKeyChar();
        int tempInt = 0;
        JTextField temp = null;

        if (!((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
            getToolkit().beep();
            e.consume();
        }
        try {
            temp = (JTextField) e.getSource();
            System.out.println(temp.getText());
            tempInt = (Integer.parseInt(temp.getText().toString()));
        } catch (NumberFormatException e1) {

        } finally {
            if (tempInt > (Short.MAX_VALUE * 2)) {
                 getToolkit().beep();
                 e.consume();
                temp.setText(temp.getText().substring(0, temp.getText().length() - 1));

                invalidate();
            }

        }
    }

};

推荐答案

因此,不是您发现的KeyListener,它是不可靠的,并且会引起很多讨厌的副作用(以及可能的文档突变例外:P ),我们应该使用DocumentFilter,因为这正是它的设计目的

So, instead of a KeyListener, which you've found, is unreliable and will cause lots of nasty side effects (and possible Document Mutation exceptions :P), we should use a DocumentFilter, cause that's what it's designed for

public class ShortFilter extends DocumentFilter {

    protected boolean valid(String text) {


        boolean valid = true;
        for (char check : text.toCharArray()) {

            if (!Character.isDigit(check)) {

                valid = false;
                break;

            }

        }

        if (valid) {

            int iValue = Integer.parseInt(text);

            valid = iValue <= (Short.MAX_VALUE * 2);

        }

        return valid;

    }

    @Override
    public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {

        StringBuilder sb = new StringBuilder(fb.getDocument().getText(0, fb.getDocument().getLength()));
        sb.insert(offset, text);

        if (valid(sb.toString())) {

            super.insertString(fb, offset, text, attr);

        }

    }

    @Override
    public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {

        if (length > 0) {

            StringBuilder sb = new StringBuilder(fb.getDocument().getText(0, fb.getDocument().getLength()));

            sb.delete(offset, length);
            sb.insert(offset, text);

            if (valid(sb.toString())) {

                super.replace(fb, offset, length, text, attrs);

            }

        } else {

            insertString(fb, offset, text, attrs);

        }

    }
}

您需要将其应用于字段的文档

You will need to apply this to the field's document

((AbstractDocument) field.getDocument()).setDocumentFilter(new ShortFilter());

我要结帐

  • http://www.jroller.com/dpmihai/entry/documentfilter
  • http://docs.oracle.com/javase/7/docs/api/javax/swing/text/DocumentFilter.html

更多信息

十进制包含的更新

基本上,如果要允许包含小数,则需要在valid方法中允许使用该字符.

Basically, if you want to allow the inclusion of a decimal, you need to allow for the character in the valid method.

您还需要检查当前文档的内容

You also need to check the current document's contents

StringBuilder sb = new StringBuilder(fb.getDocument().getText(0, fb.getDocument().getLength()));

// Update the StringBuilder as per noraml
// Check valid as per normal

if (text.contains(".") && sb.contains(".")) {
  // already have decimal place
} else {
  // Business as usual...
}

这篇关于JTextField只接受有效的未签名短裤吗? (使用KeyAdapter)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆