Created
May 25, 2011 19:53
-
-
Save karanmalhi/991769 to your computer and use it in GitHub Desktop.
Example showing property editors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.learnquest.propertyeditor; | |
import java.beans.PropertyEditor; | |
import java.beans.PropertyEditorSupport; | |
public class Test { | |
public static void main(String[] args) { | |
Person p = new Person("Sarah:Garwood"); | |
System.out.println(p.toString()); | |
System.out.println(p.getName().getFirstName()); | |
System.out.println(p.getName().getLastName()); | |
} | |
} | |
class Name { | |
private String firstName; | |
private String lastName; | |
public Name() {} | |
public Name(String firstName, String lastName) { | |
super(); | |
this.firstName = firstName; | |
this.lastName = lastName; | |
} | |
public String getFirstName() { | |
return firstName; | |
} | |
public void setFirstName(String firstName) { | |
this.firstName = firstName; | |
} | |
public String getLastName() { | |
return lastName; | |
} | |
public void setLastName(String lastName) { | |
this.lastName = lastName; | |
} | |
} | |
class NameEditor extends PropertyEditorSupport { | |
// firstName:lastName | |
@Override | |
public void setAsText(String text) throws IllegalArgumentException { | |
String[] split = text.split(":"); | |
Name name = new Name(split[0], split[1]); | |
setValue(name); | |
} | |
@Override | |
public String getAsText() { | |
Name name = (Name) getValue(); | |
if(name == null) | |
return null; | |
return name.getFirstName()+":"+name.getLastName(); | |
} | |
} | |
class Person { | |
private Name name; | |
private PropertyEditor nameEditor = new NameEditor(); | |
public Person() {} | |
public Person(String name){ | |
nameEditor.setAsText(name); | |
this.name = (Name) nameEditor.getValue(); | |
} | |
public Person(Name name) { | |
super(); | |
this.name = name; | |
} | |
public Name getName() { | |
return name; | |
} | |
public void setName(Name name) { | |
this.name = name; | |
} | |
@Override | |
public String toString() { | |
// string representation of Name | |
return nameEditor.getAsText(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment