1

I have a class which only allows integers with limited amount. The problem is, class is doing its work but when I use multiple objects, it only takes the last objects limitation number and applies to others.

I also couldn't get rid of static warnings.

Code is ;

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

            }
        }
    }
}

How I call it on another class ;

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

The result is no1, no2, and no3 has (10) as a limitation.

Example:
no1: 1234567890 should be max len 12345
no2: 1234567890 should be max len 1234567
no3: 1234567890 it's okay
Lunatic Fnatic
  • 661
  • 2
  • 6
  • 17

1 Answers1

2

It's because your limitInt is static, which means it has the same value for all instances of that class (What does the 'static' keyword do in a class?). Make it non-static, and each instance of your class will have their own value for it.

If you want to use limitInt in the inner class UpperCaseDocument, then make that class non-static as well. However, if you do that, each instance of UpperCaseDocument will also have an instance of LimitedIntegerTF associated with it.

Community
  • 1
  • 1
gla3dr
  • 2,179
  • 16
  • 29