2013-04-05 25 views
0

我有一個JTextField,其中用戶必須在那輸入一個號碼如何確定JTextfield的整數值?

我想檢查一下這個值是否包含* * Integer **

下面是代碼:

JTextField Tex_amount=new JTextField(); 
. 
. 
. 
String s=Tex_amount.getText(); 
int a=Integer.parseInt(s); 

的問題是,如果用戶在字段中輸入一個字符串我將與錯誤臉: java.lang.NumberFormatException。那我該如何檢查價值?

+1

做一些驗證,其中用戶只能從鍵盤輸入數字。 – subodh 2013-04-05 07:31:18

+3

這裏:http://stackoverflow.com/questions/11093326/restricting-jtextfield-input-to-integers限制輸入只有整數 – 2013-04-05 07:33:23

+0

另請參閱http://stackoverflow.com/a/13424140/1076463 – Robin 2013-04-05 09:01:34

回答

3

您可以使用嘗試..catch

try{ 
    int a = Integer.parseInt(s); 
} 
catch(ArithmeticException e){ 
    //Handel error here 
} 
+0

真的謝謝: - ) – Salman 2013-04-05 07:57:38

+0

歡迎..... :) – commit 2013-04-05 09:11:58

7

有三種方式

  1. 使用的JFormattedTextField與數字格式化

  2. 使用的JSpinner與SpinnerNumberModel的

  3. 添加的DocumentFilter平淡的JTextField