只是为了好玩,用 InputVerifier 实现了一个穷人的单向绑定:注意 inputVerifier 保证在转移焦点之前被访问(并且似乎在当前版本的 jdk 中工作 - 在旧版本中有一些问题),所以只要提交操作中涉及焦点转移,在验证器中进行任何更新都应该是安全的:
验证者和一些粗略的数据对象:
/**
* Very simple uni-directional binding (component --> data) class.
*/
public static class BindingVerifier extends InputVerifier {
private RawData data;
private boolean first;
public BindingVerifier(RawData data, boolean first) {
this.data = data;
this.first = first;
}
@Override
public boolean shouldYieldFocus(JComponent input) {
String text = ((JTextComponent) input).getText();
if (first) {
data.one = text;
} else {
data.two = text;
}
return true;
}
@Override
public boolean verify(JComponent input) {
return true;
}
}
public static class RawData {
String one;
String two;
public RawData(String one, String two) {
this.one = one;
this.two = two;
}
public String toString() {
return one + "/" + two;
}
}
用法:
final RawData data = new RawData(null, null);
JTextField first = new JTextField(20);
first.setInputVerifier(new BindingVerifier(data, true));
JTextField second = new JTextField(20);
second.setInputVerifier(new BindingVerifier(data, false));
Action commit = new AbstractAction("commit") {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(data);
}
};
JComponent form = new JPanel();
form.add(first);
form.add(second);
form.add(new JButton(commit));