ty.create("${" + sourceProperty + "}"),
field, BeanProperty.create("text"));
bindingGroup.addBinding(binding);
bindingGroup.bind();
return new JXLayer<jTextComponent>(field, new HibernateValidationUI(
sourceObject, sourceProperty));
}
}
createTextField()方法主要将给定对象属性的值与JTextField的text绑定,然后将JTextField纳入到 JXLayer的管理之下。这样一来,一旦用户在JTextField里面修改数据,这个改变就会同步到该对象属性 上,然后就引发了前面描述的一系列逻辑,最终改变的数据就会被Hiberante Validator加以验证。
最后,我们可以编写一个Demo application来看看效果如何,代码如下:
package de.jingge.main;
import de.jingge.domain.Country;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.JTextComponent;
import net.miginfocom.swing.MigLayout;
import org.jdesktop.beansbinding.BindingGroup;
import org.jdesktop.jxlayer.JXLayer;
import static de.jingge.view.GuiComponentFactory.*;
public class ValidationApplicaton {
private BindingGroup bg;
private Country country;
private JXLayer<jTextComponent> codeField;
private JXLayer<jTextComponent> nameField;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
System.err.println(
"Nimbus L&F does not support. Default L&F will be used.");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ValidationApplicaton app = new ValidationApplicaton();
JFrame frame = new JFrame("Demo Validation Application");
frame.setPreferredSize(new Dimension(360, 150));
frame.getContentPane().add(app.buildPanel(), BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setCenter(frame);
frame.setVisible(true);
frame.pack();
}
private static void setCenter(JFrame frame) {
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
// Calculate the frame location
int x = (screenSize.width - (int) frame.getPreferredSize().getWidth()) / 2;
int y = (screenSize.height - (int) frame.getPreferredSize().getHeight()) / 2;
// Set the new frame location
frame.setLocation(x, y);
}
public ValidationApplicaton() {
country = new Country();
bg = new BindingGroup();
}
p
|