2010-08-22 33 views
1

我正在爲用戶提供「實時」驗證的表單上,我遇到了一個問題。InputVerifier和多個字段

目標是在字段附近放置一個標籤(本例中爲JSpinner),以便以與基於JavaScript的驗證程序相同的方式向用戶顯示接受或拒絕數據。

的問題是,對於archieving此,我需要設置的值對應的標籤,我發現這樣做是創造儘可能多的核查員作爲字段的唯一方式,這種方式:

class MyVerifier extends InputVerifier{ 

    static final double MAX_VALUE = 30; 

    @Override 
    public boolean verify(JComponent input) { 
     JTextField tf = (JTextField) input; 
     Double value = Double.parseDouble(tf.getText().replace(',', '.')); 
     return (value>1); 
    } 

    @Override 
    public boolean shouldYieldFocus(JComponent input) { 
     boolean isValid = super.shouldYieldFocus(input); 
    if (isValid) { 
      jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("resources/accept.png"))); 
      jLabel1.setText(""); 
    } else { 
      jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("resources/exclamation.png"))); 
      jLabel1.setText("The number of items must be greater than 1"); 
    } 
     return true; 
    } 
} 

然後,相同的代碼jLabel2 ...它必須是另一種方式來做到這一點。

在此先感謝。

回答

1

您可以爲文本字段及其相關標籤組件添加一個Hashmap。然後,在shouldYieldFocus方法中,檢索正在驗證的文本字段的相關標籤。然後可以適當地設置標籤的文字/圖標。

您可能還需要一個包含錯誤標籤和文本消息的secound Hashmap。

+0

完美,謝謝! – 2010-08-23 06:35:41

1

您也可以使用JDialog作爲您正在驗證的JComponent旁邊的彈出窗口。這個彈出的JDialog將有一個JLabel,它將封裝你想要顯示在各個Jcomponent旁邊的消息。你所要做的就是計算彈出框相對於你正在驗證的Jcomponent的位置。

你可以找到一個很好的例子here