我正在编写一个表单,为用户提供“实时”验证,我有一个问题。
目标是在字段附近放置一个标签(在本例中是JSpinner),以显示用户是否接受或拒绝数据,就像基于javascript的验证器所做的那样。
问题是,为了归档这一点,需要为相应的标签设置值,而我找到的唯一方法是创建与字段一样多的验证器,这种方式:
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的相同代码.这肯定是另一种方法。
提前谢谢。
发布于 2010-08-22 21:35:31
您可以为文本字段及其相关的label组件提供一个Hashmap。然后,在shouldYieldFocus方法中,检索正在验证的文本字段的相关标签。然后,您可以适当地设置标签的文本/图标。
您可能还需要一个包含标签和错误文本消息的。
发布于 2010-08-24 15:46:52
您还可以使用JDialog作为正在验证的JComponent旁边的弹出窗口。这个弹出的JDialog将有一个JLabel,它将封装您想要显示在各自Jcomponent旁边的消息。您所要做的就是计算弹出窗口相对于正在验证的Jcomponent的位置。
您可以找到一个很好的示例这里
https://stackoverflow.com/questions/3543458
复制相似问题