这是一个非常简单的类:
static public class Bean1
{
final private String name;
final private Bean1 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; }
}
我想做的是将一些 UI 组件绑定(bind)到 BeanAdapter<Bean1>
(参见 com.jgoodies.binding.beans.BeanAdapter
)这样如果 BeanAdapter 指向 Bean1 bean1
,然后我就可以显示
bean1.name (blank if null)
bean1.parent.name (blank if null or if bean1.parent is null)
bean1.favoriteNumber
字段 name
和favoriteNumber
很容易,但我对如何显示父名称感到困惑。看起来 BeanAdapter 只允许我绑定(bind)到直接存在于 Bean1 中的属性。但这是很差的模块化,它迫使我每次想要绑定(bind)到 bean 的新方面时都添加 getter/setter 函数。
我想做的是编写一个知道如何访问 bean 的帮助器类,但我很困惑如何让它与 Bean1 和 BeanAdapter 一起正常工作。
如果这个问题不太清楚,我很抱歉,我不知道这些词汇,而且对绑定(bind)的概念有点模糊。
最佳答案
这里的问题是绑定(bind)以两种方式工作:从model到ui,以及从ui到model强>。
就您而言,您将如何处理某人首次在绑定(bind)到 parent.name 的文本字段中输入信息的情况?您会即时创建父级吗?你会报错吗?
如果您知道在这种情况下该怎么做(例如,创建具有该名称的父级),您可以使用 com.jgoodies.binding.value.AbstractConverter
转换 Bean1
到 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) { ... }
}
您可以像使用普通 ValueModel 一样使用此转换器:
Bindings.bind(uifield,"value",
new ParentNameConverter(beanAdapter.getValueModel("parent")));
关于Java bean 绑定(bind) : adapters?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2639283/