2015-02-06 32 views
1

我有一個只允許有限數量的整數的類。問題是,課程正在完成它的工作,但是當我使用多個對象時,它只採用最後一個對象限制數並適用於其他對象。定製JTextfield - 只限於整數

我也無法擺脫靜態警告。

代碼是;

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

結果是no1no2,和no3具有(10)作爲限制。

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

回答

2

這是因爲你的limitIntstatic,這意味着它具有該類(What does the 'static' keyword do in a class?)的所有實例相同的值。使其成爲非靜態的,並且您的課程的每個實例都將擁有自己的值。

如果您想在內部類UpperCaseDocument中使用limitInt,那麼使該類非靜態。但是,如果您這樣做,UpperCaseDocument的每個實例也都會有一個與之關聯的LimitedIntegerTF的實例。