有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java自定义JTextfield Only整数,有限制

我有一个类,它只允许数量有限的整数。问题是,类正在执行它的工作,但当我使用多个对象时,它只接受最后一个对象限制数,并应用于其他对象

我也无法摆脱静态警告

代码是

public class LimitedIntegerTF extends JTextField {

    private static final long serialVersionUID = 1L;
    private static int limitInt;
    public LimitedIntegerTF() {
        super();
    }

    public LimitedIntegerTF(int limitInt) {
        super();
        setLimit(limitInt);
    }

    @SuppressWarnings("static-access")
    public final void setLimit(int newVal) 
    {
        this.limitInt = newVal;
    }

    public final int getLimit() 
    {
        return limitInt;
    }

    @Override
    protected Document createDefaultModel() {
        return new UpperCaseDocument();
    }

    @SuppressWarnings("serial")
    static class UpperCaseDocument extends PlainDocument {

        @Override
        public void insertString(int offset, String strWT, AttributeSet a)
                throws BadLocationException {

            if(offset < limitInt){
                if (strWT == null) {
                    return;
                }

                char[] chars = strWT.toCharArray();
                boolean check = true;

                for (int i = 0; i < chars.length; i++) {

                    try {
                        Integer.parseInt(String.valueOf(chars[i]));
                    } catch (NumberFormatException exc) {
                        check = false;
                        break;
                    }
                }

                if (check)
                    super.insertString(offset, new String(chars),a);

            }
        }
    }
}

我在另一节课上如何称呼它

final LimitedIntegerTF no1 = new LimitedIntegerTF(5);
final LimitedIntegerTF no2 = new LimitedIntegerTF(7);
final LimitedIntegerTF no3 = new LimitedIntegerTF(10);

结果是no1no2no3(10)作为限制

Example:
no1: 1234567890 should be max len 12345
no2: 1234567890 should be max len 1234567
no3: 1234567890 it's okay

共 (1) 个答案

  1. # 1 楼答案

    这是因为limitIntstatic,这意味着它对该类(What does the 'static' keyword do in a class?)的所有实例都具有相同的值。让它成为非静态的,你的类的每个实例都有自己的值

    如果您想在内部类UpperCaseDocument中使用limitInt,那么也要使该类成为非静态类。但是,如果这样做,每个UpperCaseDocument实例也将有一个LimitedIntegerTF实例与其关联