Here's a really simple class:
static public class Bean1
{
final private String name;
final private Bea开发者_如何学Gon1 parent;
private int favoriteNumber;
public String getName() { return this.name; }
public Bean getParent() { return this.parent; }
public int getFavoriteNumber() { return this.favoriteNumber; }
public void setFavoriteNumber(int i) { this.favoriteNumber = i; }
}
What I would like to do is to bind some UI components to a BeanAdapter<Bean1>
(see com.jgoodies.binding.beans.BeanAdapter
) so that if the BeanAdapter points to Bean1 bean1
, then I can display
bean1.name (blank if null)
bean1.parent.name (blank if null or if bean1.parent is null)
bean1.favoriteNumber
The fields name
and favoriteNumber
are easy, but I'm confused about how to display the parent name. It looks like BeanAdapter only lets me bind to properties which exist directly in Bean1. But this is poor modularity and it forces me to add getter/setter functions every time I want to bind to a new aspect of the bean.
What I would like to do is write a helper class which knows how to access a bean, and am confused how to get it to work properly with Bean1 and BeanAdapter.
I'm sorry if this question is not more clear, I don't know the vocabulary and am a little hazy on the concepts of binding.
The problem here is that binding works in both ways: from model to ui, and from ui to model.
In your case, how would you deal with someone entering information for the first time in a textfield that's binded to parent.name? Would you create a parent on the fly? Would you give an error?
If you know what to do in that situation (e.g. create a parent with that name), you could use a com.jgoodies.binding.value.AbstractConverter
to convert a Bean1
to a String
:
public class ParentNameConverter extends AbstractConverter {
/**
* Converts a value from the subject to the type or format used
* by this converter.
*
* @param subjectValue the subject's value
* @return the converted value in the type or format used by this converter
*/
public Object convertFromSubject(Object subjectValue) { ... }
/**
* Sets a new value on the subject, after converting to appropriate type
* or format
*
* @param newValue the ui component's value
*/
public void setValue(Object newValue) { ... }
}
You can use this converter the same way you use a normal ValueModel:
Bindings.bind(uifield,"value",
new ParentNameConverter(beanAdapter.getValueModel("parent")));
精彩评论