2011-10-26 97 views
2

如何驗證用戶輸入只包含5位數和2位小數。我使用下面的代碼來檢查5位數字,但是如何檢查2位小數。Java文本字段十進制驗證

if (!id.equals("")) { 
     try { 
      Integer.parseInt(id); 
      if (id.length() <= 5) { 
       return true; 
      } 
     } catch (NumberFormatException nfe) { 
      return false; 
     } 
    } 
+1

您可能對[JFormattedTextField]感興趣(http://download.oracle.com/javase/6/docs/api/javax/swing/JFormattedTextField.html)。 –

回答

3
if(id.matches("\\d{5}\\.\\d{2}")) 
    return true; 
return false; 
+1

除了他想要「最多5個」,而不是「完全5個」。 –

3

Swing中的任何驗證都可以使用InputVerifier執行。

  1. 首先創建自己的輸入驗證

    public class MyInputVerifier extends InputVerifier { 
        public boolean verify(JComponent input) { 
         String text = ((JTextField) input).getText(); 
         try { 
          BigDecimal value = new BigDecimal(text); 
          return (value.scale() <= Math.abs(2)); 
         } catch (NumberFormatException e) { 
          return false; 
         } 
        } 
    } 
    
  2. 則這個類的一個實例分配給您的文本字段。 (實際上任何JComponent都可以驗證)

myTextField.setInputVerifier(new MyInputVerifier()); 當然,您也可以使用匿名內部類,但如果驗證程序也用於其他組件,則普通類更好。

另請參見SDK文檔:JComponent#setInputVerifier。