这是您复制粘贴乐趣的有效解决方案:)
这是施展魔法的听众.. ;)
public class BindingListener implements DocumentListener {
private ModelObject model;
private String fieldName;
public BindingListener(ModelObject model, String fieldName) {
this.model = model;
String firstChar = String.valueOf(fieldName.charAt(0));
if (firstChar.equals(firstChar.toLowerCase())) {
fieldName = firstChar.toUpperCase()
+ fieldName.substring(1, fieldName.length());
}
this.fieldName = fieldName;
}
@Override
public void insertUpdate(DocumentEvent e) {
dataUpdated(e);
}
@Override
public void removeUpdate(DocumentEvent e) {
dataUpdated(e);
}
@Override
public void changedUpdate(DocumentEvent e) {
dataUpdated(e);
}
private void dataUpdated(DocumentEvent e) {
try {
String text = e.getDocument().getText(
e.getDocument().getStartPosition().getOffset(),
e.getDocument().getEndPosition().getOffset() - 1);
System.out.println("Entered text: " + text);
System.out.println("Field to be updated: " + fieldName);
System.out.println("Old model values: " + model);
Method method = model.getClass().getDeclaredMethod(
"set" + fieldName, String.class);
method.invoke(model, text);
System.out.println("New model values: " + model);
} catch (BadLocationException e1) {
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (InvocationTargetException e1) {
e1.printStackTrace();
}
}
}
假设您的模型对象看起来像下面的类。
public class ModelObject {
private String field1;
private String field2;
/**
* @return the field1
*/
public String getField1() {
return field1;
}
/**
* @param field1
* the field1 to set
*/
public void setField1(String field1) {
this.field1 = field1;
}
/**
* @return the field2
*/
public String getField2() {
return field2;
}
/**
* @param field2
* the field2 to set
*/
public void setField2(String field2) {
this.field2 = field2;
}
@Override
public String toString() {
return "ModelObject [field1=" + field1 + ", field2=" + field2 + "]";
}
}
假设您的 GUI 正在处理这样的代码..
JTextField textField1 = new JTextField();
textField1.setPreferredSize(new Dimension(100, 25));
JTextField textField2 = new JTextField();
textField2.setPreferredSize(new Dimension(100, 25));
panel.add(textField1);
panel.add(textField2);
ModelObject model = new ModelObject();
textField1.getDocument().addDocumentListener(new BindingListener(model, "field1"));
textField2.getDocument().addDocumentListener(new BindingListener(model, "field2"));
更新:这里还有一些示例输出..
Entered text: x
Field to be updated: Field1
Old model values: ModelObject [field1=null, field2=null]
New model values: ModelObject [field1=x, field2=null]
Entered text: y
Field to be updated: Field2
Old model values: ModelObject [field1=x, field2=null]
New model values: ModelObject [field1=x, field2=y]