楽しみのために、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));