2010-05-01 31 views

回答

29

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

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

public class MyInputVerifier extends InputVerifier { 
    @Override 
    public boolean verify(JComponent input) { 
     String text = ((JTextField) input).getText(); 
     try { 
      BigDecimal value = new BigDecimal(text); 
      return (value.scale() <= Math.abs(4)); 
     } catch (NumberFormatException e) { 
      return false; 
     } 
    } 
} 

2.然後這個類的一個實例分配給您的文本字段。 (其實任何JComponent可以得到驗證)

myTextField.setInputVerifier(new MyInputVerifier()); 

當然你也可以使用匿名內部類,但如果驗證是要在其他組件使用,也正常類是更好的。

另請參閱SDK文檔:JComponent#setInputVerifier

+1

改用'BigDecimal',然後用'scale()'檢查小數位數。 – 2010-05-01 10:59:29

+0

謝謝,我已經更新了代碼。 – 2010-05-01 11:34:37

+0

謝謝你的提示和代碼片段。我會盡量讓你知道在斷開連接的情況下 – Chandu 2010-05-01 11:43:15

0

您或許可以用DocumentListener完成相同的操作。您所要做的就是根據所需的字符串模式驗證輸入字符串。在這種情況下,該模式似乎是一個或多個數字,後跟一個句點,AND小數點後的正好是4位數。下面的代碼演示了使用DocumentListener來實現:

public class Dummy 
{ 
    private static JTextField field = new JTextField(10); 
    private static JLabel errorMsg = new JLabel("Invalid input"); 
    private static String pattern = "\\d+\\.\\d{4}"; 
    private static JFrame frame = new JFrame(); 
    private static JPanel panel = new JPanel(); 

    public static void main(String[] args) 
    { 
    errorMsg.setForeground(Color.RED); 
    panel.setLayout(new GridBagLayout()); 
    GridBagConstraints c = new GridBagConstraints(); 
    c.insets = new Insets(5, 0, 0, 5); 
    c.gridx = 1; 
    c.gridy = 0; 
    c.anchor = GridBagConstraints.SOUTH; 
    panel.add(errorMsg, c); 

    c.gridx = 1; 
    c.gridy = 1; 
    c.anchor = GridBagConstraints.CENTER; 
    panel.add(field, c); 

    frame.getContentPane().add(panel); 
    field.getDocument().addDocumentListener(new DocumentListener() 
    { 
     @Override 
     public void removeUpdate(DocumentEvent e) 
     { 
     validateInput(); 
     } 

     @Override 
     public void insertUpdate(DocumentEvent e) 
     { 
     validateInput(); 
     } 

     @Override 
     public void changedUpdate(DocumentEvent e) {} // Not needed for plain-text fields 
    }); 

    frame.setSize(200, 200); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 
    } 

    private static void validateInput() 
    { 
    String text = field.getText(); 
    Pattern r = Pattern.compile(pattern); 
    Matcher m = r.matcher(text); 
    if (m.matches()) 
    { 
     errorMsg.setForeground(frame.getBackground()); 
    } 
    else 
    { 
     errorMsg.setForeground(Color.RED); 
    } 
    } 
} 

只要文本字段不包含有效的輸入,示出像下面的圖像的錯誤信息。

invalid input

一旦輸入進行驗證,該錯誤消息將不可見。

valid input

當然,你也可以更換到任何你需要驗證動作。例如,如果輸入無效等情況下單擊按鈕,則可能需要顯示一些彈出窗口。

我將它們放在一起以顯示已經給出的答案的替代方案。可能有這種解決方案可能更適合的情況。可能有些情況下給定的答案可能更適合。但有一點是肯定的,替代品總是一件好事。