2014-01-14 53 views
1

我有一個的JFormattedTextField,我想,當我嘗試輸入一個數字,例如1002,我會四捨五入爲5的JFormattedTextField四捨五入數字

1002-> 1000

304-1最接近的倍數> 305

6-> 5

9-> 10

1-> 0

等。

我已經設置的數字格式取消分組,並接受只有數字

NumberFormat format=NumberFormat.getInstance(); 
format.setGroupingUsed(false); 
pun1[i]=new JFormattedTextField(format); //pun1 and pun2 are the arrays of FIELDS 
pun2[i]=new JFormattedTextField(format); 

我怎樣才能解決這個問題呢?

我想現場這裏面的編輯,而我寫的號碼,只是當分組人物出現!

回答

0

這適用於int參數:

public int roundToClosestFive(int num) { 
    return (int) (Math.round(num/5.0) * 5); 
} 

記住,讓你輸入你可以做字符串的int值:Integer.valueOf(string);並傳遞作爲參數傳遞給方法。有JFormattedTextField變化對焦點變化中的文本或輸入,你可以調用從PropertyChange監聽器,你可以添加到JTextFormattedTextFieldpropertyChange()方法上面的方法。像這樣的事情在propertyChange()方法:

public void propertyChange(PropertyChangeEvent e) { 
    Object source = e.getSource(); 
    if (source == pun1[i]) { 
     ((JFormattedTextField) source).setText("" 
       + roundToClosestFive(((Number)pun1[i].getValue()).intValue())); 
    } 
} 
+0

我想現場的編輯過程中這種變化,所以我寫「1003」和領域內的變化對1005 –

+0

好數,我已經加入到我的答案。那對你有用嗎?同樣,對於上述情況,您必須將焦點從「JTextFormattedField」移開,或者在字段內的文本中按Enter鍵以更改。 –

+0

不,這是行不通的:\ 如果不是JTextFormattedField,你有什麼建議? –