Wednesday, July 23, 2008

Update: Common Validation Module for Swing Application

In the last blog I have written how to build a common validation module by using the jxlayer, beansbinding, and hibernate validator. After discussing about it with the JXLayer Author Alexander Potochkin, I got a suggestion from him(thanks, Alexp :-)): we should not change the state of any component in the paint() method. This is a swing pattern.

The last version of the HibernateValidationUI contains Obviously an antipattern, where the tooltip is set in the paintLayer() method.

Today, I post here a updated version of the HibernateValidationUI and try to kill the antipattern.


/**
* @author Jing Ge
*/
public class HibernateValidationUI extends AbstractLayerUI<JTextComponent> {

private Object object;
private String propertyName;
private ClassValidator validator;
private ELProperty elProperty;
private PropertyStateListener propertyChangeHandler;
private JXLayer<JTextComponent> layer;

public HibernateValidationUI(Object obj, String propertyName) {
this.object = obj;
this.propertyName = propertyName;
propertyChangeHandler = new PropertyChangeHandler();
validator = new ClassValidator(obj.getClass());

elProperty = ELProperty.create("${" + propertyName + "}");
}

@Override
public void installUI(JComponent c) {
if (layer != null) {
throw new IllegalStateException(getClass().getSimpleName() +
" can't be shared between multiple layers");
}
super.installUI(c);
layer = (JXLayer<JTextComponent>) c;
elProperty.addPropertyStateListener(object, propertyChangeHandler);
validate();
}

@Override
public void uninstallUI(JComponent c) {
super.uninstallUI(c);
layer = null;
elProperty.removePropertyStateListener(object, propertyChangeHandler);
}

private void validate() {
InvalidValue[] validationMessages = validator.getInvalidValues(object,
propertyName);
if (validationMessages.length > 0) {
layer.getView().setToolTipText(validationMessages[0].getMessage());
return;
}
layer.getView().setToolTipText(null);
}

@Override
protected void paintLayer(Graphics2D g2, JXLayer<JTextComponent> l) {
super.paintLayer(g2, l);
if (!isValid()) {
BufferedImage image = Java2DIconFactory.createErrorIcon();
g2.drawImage(image, l.getWidth() - image.getWidth() - 1,
l.getHeight() - 8, null);
}
}

boolean isValid() {
return isBlank(layer.getView().getToolTipText());
}

/**
* a copy from the apache common lang.
* Just use the StringUtils if the common lang jar in your classpath.
*/
private boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}

class PropertyChangeHandler implements PropertyStateListener {

@Override
public void propertyStateChanged(PropertyStateEvent pse) {
validate();
setDirty(true);
}
}
}


There are some changes in the class:

1. The class holds a reference of the JXlayer instance, because it will be used while we validate the property. The reference will be injected when installUI() method is called.
2. A new method validate() is added, which will validate the property and set the tooltip appropriately.
3. The validate() method should be called in two places. One is just after the JXLayer instance is injected and another is when the property is changed, i.e. in the propertyStateChange(PropertyStateEvent) method.
4. Now we simply use the tooltip text of the managed text component for checking whether the value of the property is valid.
5. In the paintLayer() method we will only paint the error icon(when the the content of the property is invalid). No state of any component will be changed here.
6. like the comment says, the isBlank() method is a copy from the apache common lang. If the common lang jar is in your classpath, just call the StringUtils.isBlank() method.

17 comments:

Alexander said...

Hello Jing

I like this version!

the only recommendation I have
is specifying the fact that this layerUI is not shareable between layers, and adding a checking in installUI() to prevent incorrect setting this ui to multiple layer,
just like is implemented in AbstractBufferedLayerUI

Thanks
alexp

JingGe said...

Hello Alexp

Thanks a lot. The check is added.

Regards!
Jing

chengja said...

The All-Star thirddofus kamasdofus kamasbaseman said in an interviewkamas dofusacheter dofuswith ESPN that he used steroids with the Texas Rangers for three years,from 2001-03,in an attemptbuy kamasacheter kamasto justify his status as the game's highest-paid player after signing a 10-year.

chengja said...

Back then it wasworld of warcraft golda different culture,Rodriguezcheap wow goldsaid.It waswow orvery loose.I was young.I waswow power levelingstupid.

chengja said...

He said he quitbuy wow goldcheap wow goldafter 2003,hiswow power levelingdofus kamasfirst of three AL MVP seasons,because I've provedbuy ffxi gilLord of the Rings Online goldto myself and to everyone that I don't need any of that.

chengja said...

When I arrivedwow goldin Texas in 2001,Iwow goldfelt an enormous amount of pressure.I feltwow goldwow goldlike I had all the weightwow goldof the world on top of me and I needed to perform.

xw said...

By the way, I recommend you buy the cheapest Atlantica online Gold and Atlantica power leveling from us where the prices here are low. So if you have the Atlantica Gold is useful to your level spear and then you should buy Atlantica online Gold. In addition if you need to buy goods for your characters, the game provides you the cheap Atlantica online Gold. And the last, you can make the fun of the Atlantica online money in the Atlantica online world.
Follow the guide below, you will have a better experience in dofus kamas. Because of Bambooto attack with both earth and wind damage, with also heals kamas. There are some cheap kamas in the Dofus and that is very useful. The best part is that bulbiflor can drop bulbiflor magic bark, which sells for 50000 dofus gold. They sell well kamas anytime too, so you can buy dofus kamas at anytime.

milf said...

black mold exposureblack mold symptoms of exposurewrought iron garden gatesiron garden gates find them herefine thin hair hairstylessearch hair styles for fine thin hairnight vision binocularsbuy night vision binocularslipitor reactionslipitor allergic reactionsluxury beach resort in the philippinesafordable beach resorts in the philippineshomeopathy for eczema.baby eczema.save big with great mineral makeup bargainsmineral makeup wholesalersprodam iphone Apple prodam iphone prahacect iphone manualmanual for P 168 iphonefero 52 binocularsnight vision Fero 52 binocularsThe best night vision binoculars herenight vision binoculars bargainsfree photo albums computer programsfree software to make photo albumsfree tax formsprintable tax forms for free craftmatic air bedcraftmatic air bed adjustable info hereboyd air bedboyd night air bed lowest pricefind air beds in wisconsinbest air beds in wisconsincloud air bedsbest cloud inflatable air bedssealy air beds portableportables air bedsrv luggage racksaluminum made rv luggage racksair bed raisedbest form raised air bedsbed air informercialsbest informercials bed airmattress sized air bedsbestair bed mattress antique doorknobsantique doorknob identification tipsdvd player troubleshootingtroubleshooting with the dvd playerflat panel television lcd vs plasmaflat panel lcd television versus plasma pic the bestadjustable bed air foam The best bed air foam hoof prints antique equestrian printsantique hoof prints equestrian printsBuy air bedadjustablebuy the best adjustable air bedsair beds canadian storesCanadian stores for air bedsmigraine causemigraine treatments floridaflorida headache clinicdrying dessicantair drying dessicantdessicant air dryerpediatric asthmaasthma specialistasthma children specialistcarpet cleaning dallas txcarpet cleaners dallascarpet cleaning dallasvero beach vacationvero beach vacationsbeach vacation homes veroms beach vacationsms beach vacationms beach condosmaui beach vacationmaui beach vacationsmaui beach clubbeach vacationsyour beach vacationscheap beach vacationsbob hairstylebob haircutsbob layeredpob hairstylebobbedclassic bobCare for Curly HairTips for Curly Haircurly hair12r 22.5 best pricetires truck bustires 12r 22.5washington new housenew house houstonnew house san antonionew house venturanew houston house houston house txstains removal dyestains removal clothesstains removalteeth whiteningteeth whiteningbright teethjennifer grey nosejennifer nose jobscalebrities nose jobsWomen with Big NosesWomen hairstylesBig Nose Women, hairstyles

qwe said...

runescape gold of RS Online Game, we have made several changes to Fun Orb. If you wish to buy runescape to explore other spell books, you should subscribe as a Fun Orb member. Shattered Plans - a galaxy-spanning strategy epic that use rs gold to allow up to six players to battle for supremacy. We only plan to pay cheap rs gold when we feel you will appreciate the updates. And we certainly feel that these changes and some runescape money are worth telling you about.
Scions Of Fate gold is sometimes need to pay for in this Scions of Fate game. For example in this game, we have to buy sof gold to exchange premium in order to protect our character. The only part of this game will require you to pay SOF gold but they are optional for you to choose in the premium store. One very common item bought with cheap SOF gold at the store would be a pet. The Gameim.com is offering you with Scions Of Fate money and all kinds of cheap game gold.

said...

You know ,I have some Anarchy credits, and my friend also has some
Anarchy Online credits, do you know they have the same meaning,Both of them can be called
Anarchy gold,I just want to buy AO credits, because there are many cheap Anarchy online gold.

said...

You know ,I have some Tales Of Pirates gold, and my friend also has some
Tales Of Pirates money, do you know they have the same meaning, I just want to
buy Tales Of Pirates Gold, because there are many
cheap Tales Of Pirates gold

春香 said...

Making requiem gold is the old question : Honestly there is no fast way to make lots of requiem lant . Sadly enough a lot of the people that all of a sudden come to with millions of requiem money almost overnight probably duped . Although there are a lot of ways to make lots of requiem online gold here I will tell you all of the ways that I know and what I do to buycheap requiem lant

春香 said...

As a new player , you may need some game guides or information to enhance yourself.
Rose zuly is one of the hardest theme for every class at the beginning . You must have a good way to manage your rose zulie.If yor are a lucky guy ,you can earn so many rose online zuly by yourself . But if you are a not , I just find a nice way to get rose online zulie. If you need , you can Arua ROSE zuly at our website . Go to the related page and check the detailed information . Once you have any question , you can connect our customer service at any time .

lanzi said...

I can get Megaten Gold cheaply.
Yesterday i bought Megaten online Gold for my brother.
i hope him like it. i will give Megaten money to him
as birthday present. i like the cheap Megaten Gold very much.
I usuallybuy Megaten Gold and keep it in my store.
I enjoy the Megaten online money.

I can getmabinogi goldcheaply,
Yesterday i boughtmabinogi online gold for my brother.
i hope him like it. i will give mabinogi money to him
as birthday present. i like the cheap mabinogi very much.
I usually buy mabinogi gold and keep it in my store.

yanhui said...

Once I played flyff, I did not know how to get strong, someone told me that you must have flyff penya. He gave me some flyff money, he said that I could buy flyff penya, but I did not have money, then I played it all my spare time. From then on, I got some flyff gold, if I did not continue to play it, I can sell cheap penya to anyone who want.


Once I played flyff, I did not know how to get strong, someone told me that you must have flyff penya. He gave me some flyff money, he said that I could buy flyff penya, but I did not have money, then I played it all my spare time. From then on, I got some flyff gold, if I did not continue to play it, I can sell cheap penya to anyone who want.

rhtehe said...

Do you know the eve isk, in the game you need the eve online isk. It can help you increase your level. My friends always asked me how to buy eve online isk, and I do not know he spend how much money to buy isk, when I see him in order to play the game and search which the place can buy the cheap eve isk. I am happy with him.
Do you know the fiesta Gold, in the game you need the
fiesta money. It can help you increase your level. My friends always asked me how to buy fiesta Gold, and I do not know he spend how much money to buy the fiesta online gold, when I see him in order to play the game and search which the place can buy the
fiesta online money. I am happy with him.

yanran said...

Your blog is very good, it's the best blog I've ever seen, thank you!
By the way, do you like polo shirts, which are very chic, especially the polo t shirts, I love them very much. I also like playing tennis rackets, it can keep healthy, what do you like to do?
polo t shirts women
polo t shirts on sale
polo t shirts for women
polo shirts on sale
polo shirts men
men's polo shirt
men polo shirt
mens polo shirts
mens polo shirt
cheap polo shirts
discount polo shirts
men's polo shirts
women's polo shirts
cheap tennis racket
discount tennis racket
prince tennis racquet
head tennis rackets
wilson tennis racket
babolat tennis racquet