2012-10-19 53 views
0

我編寫了一個gui,我想用JFormattedTextField來驗證我的輸入爲double值,但amountFormatter並沒有給我輸入正確的輸入。所以我試圖用(「##########」)創建一個自己的Formatter,它給了我一個10位數的數字,但是我無法驗證double值(因爲它們通常有一個'。') ...如何在jtextfield中嚴格限制輸入值爲double值?

所以我的問題是:如何簡單地使用Jformatted TextFields驗證double值,還是使用另一個Swing組件更容易?

UPDATE THX爲你的偉大的答案!但是,是否有可能使用JFormatted TextField的解決方案?

+3

你有沒有考慮一個'JSpinner'適當的模型開始?另請注意,它被稱爲Swing,而不是SWING。不需要關心它。 –

+1

另一個可能的解決方案是爲此使用一個'DocumentFilter'。這個網站上有很多這樣的例子,其中包括我的一些例子。例如:[here](http://stackoverflow.com/a/11093360/522444) –

+0

是否有可能使用JFormatted TextField的解決方案?順便說一句。對不起大聲說Swing,只是編輯它;) – maximus

回答

1

我已經實現了基於JFormattedTextField的數字字段。

它們還支持最小值和最大值。

也許你發現它們非常有用(庫是開源的):

http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JRealNumberField.html

http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JDoubleField.html

http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JFloatField.html

http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JLocalizedRealNumberField.html

http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JLocalizedDoubleField.html

http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JLocalizedFloatField.html

http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JWholeNumberField.html

http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JByteField.html

http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JIntegerField.html

http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JLongField.html

http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JShortField.html

教程:

http://softsmithy.sourceforge.net/lib/docs/tutorial/swing/number/index.html

更多信息:

http://puces-blog.blogspot.ch/2012/07/news-from-software-smithy-version-02.html

首頁:

http://www.softsmithy.org

下載:

http://sourceforge.net/projects/softsmithy/files/softsmithy/

Maven的:

<dependency> 
    <groupId>org.softsmithy.lib</groupId> 
    <artifactId>softsmithy-lib-core</artifactId> 
    <version>0.2</version> 
</dependency> 
+2

爲什麼你需要爲每個數字類型擴展'JFormattedTextField',當你可以通過提供正確的格式來實現相同的'Format' – Robin

+0

@Robin在大多數情況下不起作用,JSpinner和JFormmatedTextField是邪惡的 – mKorbel

+0

@Robin根據我的經驗,這並不容易。例如。這些字段具有取決於類型的set/getXyzValue。最小值和最大值取決於數據類型。您可以在這裏找到格式化程序和工廠:http://softsmithy.sourceforge.net/lib/current/docs/api/softsmithy-lib-core/org/softsmithy/lib/swing/text/package-frame.html – Puce

2

編輯

你可以用

NumberFormat format = NumberFormat.getNumberInstance(); 
format.setGroupingUsed(false); 
format.setGroupingUsed(true);// or add the group chars to the filter 
format.setMaximumIntegerDigits(10); 
format.setMaximumFractionDigits(2); 
format.setMinimumFractionDigits(5); 
format.setRoundingMode(RoundingMode.HALF_UP); 
+0

什麼可以「爲JFormattedTextField設置適當的數字格式化程序」雙值是什麼? – maximus

+0

請看我的編輯,立即停止呼喊(!!!),真的.... – mKorbel