制作一个允许用户更新编辑并从表单中删除客户详细信息的表单,有没有办法使用格式化文本字段或任何代码来简单地验证必填字段?
Not out of the box. And it all depends a bit on what you want to do after validation, eg show a message or make the field background red, ...
But simplest way would be to create a validate method in which you handle all validations, and call the validate method from listeners attached to your components and possible buttons as you like.
Rudimentary sample:
private void createForm(){
...
textField1.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
validate();
}
public void removeUpdate(DocumentEvent e) {
validate();
}
public void insertUpdate(DocumentEvent e) {
validate();
}
});
JButton button = new JButton("Next");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean valid = validate();
if(valid) {
next();
}
}
});
...
}
private boolean validate(){
StringBuilder errorText = new StringBuilder();
if(textField1.getText().length() == 0){
errorText.append("Textfield 1 is mandatory\n");
field1.setBackground(Color.red);
}
if(textField2.getText().length() == 0){
errorText.append("Textfield 2 is mandatory");
field2.setBackground(Color.red);
}
// Show the errorText in a message box, or in a label, or ...
return errorText.lenght() == 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.