就可 以了,我称这个类为HibernateValidationUI,代码如下:
package de.jingge.view;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.text.JTextComponent;
import org.hibernate.validator.ClassValidator;
import org.hibernate.validator.InvalidValue;
import org.jdesktop.beansbinding.ELProperty;
import org.jdesktop.beansbinding.PropertyStateEvent;
import org.jdesktop.beansbinding.PropertyStateListener;
import org.jdesktop.jxlayer.JXLayer;
import org.jdesktop.jxlayer.plaf.AbstractLayerUI;
/**
* Header:
* Description: A layerUI which will validate the referenced property value of
* the object each time when the paint() method is called.
* The value of the given object property will be observed.
* Note: This UI works only with {@link JXLayer}. Any change of the property
* will force repainting the UI. The work process looks like: property changed ->
* jxlayer will be repainted -> the paint() method of this UI will be called.
* The logic of validation will be handled by the Hibernate validator
* framework.
*
*/
public class HibernateValidationUI extends AbstractLayerUI<jTextComponent> {
private Object object;
private String propertyName;
private ClassValidator validator;
private ELProperty elProperty;
private PropertyStateListener propertyChangeHandler;
public HibernateValidationUI(Object obj, String propertyName) {
this.object = obj;
this.propertyName = propertyName;
propertyChangeHandler = new PropertyChangeHandler();
validator = new ClassValidator(obj.getClass());
elProperty = ELProperty.create("${" + propertyName + "}");
}
public void installUI(JComponent c) {
super.installUI(c);
elProperty.addPropertyStateListener(object, propertyChangeHandler);
}
public void uninstallUI(JComponent c) {
super.uninstallUI(c);
elProperty.removePropertyStateListener(object, propertyChangeHandler);
}
protected void paintLayer(Graphics2D g2, JXLayer<jTextComponent> l) {
super.paintLayer(g2, l);
InvalidValue[] validationMessages = validator.getInvalidValues(object,
propertyName);
if (validationMessages.length > 0) {
BufferedImage image = Java2DIconFactory.createErrorIcon();
g2.drawImage(image, l.getWidth() - image.getWidth() - 1,
l.getHeight() - 8, null);
l.getView().setToolTipText(validationMessages[0].getMessage());
return;
}
l.getView().setToolTipText(null);
}
boolean isValid() {
return validator.getInvalidValues(object, propertyName).length == 0;
}
class PropertyChangeHandler implements PropertyStateListener {
@Override
public void propertyStateChanged(PropertyStateEvent pse) {
setDirty(true);
}
}
}
Swing通用数据验证模块(4)
时间:2011-08-13 葛京
这个HibernateValidationUI类只有一个构建器,它接收两个参数,一个是source object,也就是我 们要修改的那个Bean类的实例 |