只是爲了好玩,窮人使用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));
什麼是'FocusOut'?我從未聽說過這件事。 – camickr 2013-04-10 15:39:13
最近的QA顯示[窮人的表單驗證](http://stackoverflow.com/a/14041811/203657) - 對於更多的演化控制考慮使用像f.i這樣的驗證框架。 JGoodies數據。不是我每天仔細閱讀;-)只是注意到你的問題是關於控制綁定與驗證:將提交操作包裝到SwingUtilities.invokeLater應該保證在提交之前首先實際將字段值傳遞給數據類。 – kleopatra 2013-04-10 15:48:49