我使用Netbeans
IDE编写Java代码。
我想对jFormattedTextField.
有两个jFormattedTextFields
。一个是Start Date(date1)
。其他是End Date(date2)
。现在我想将最小日期限制为“结束日期”。如果有人将2015-07-07
类型设为Start Date
,则必须限制为过去几天(2015-07-06,05,04 days)
。
答案 0 :(得分:0)
使用DocumentFilter添加验证:
final JFormattedTextField startDateField = ...;
JFormattedTextField endDateField = ...;
((AbstractDocument)endDateField.getDocument()).setDocumentFilter(new DocumentFilter(){
@Override
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException{
StringBuilder content = new StringBuilder(fb.getDocument().getText(0, fb.getDocument().getLength()));
content.replace(offset, offset + length, "");
if(isValidEndDate(content.toString()))
super.remove(fb, offset, length);
}
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException{
StringBuilder content = new StringBuilder(fb.getDocument().getText(0, fb.getDocument().getLength()));
content.insert(offset, string);
if(isValidEndDate(content.toString()))
super.insertString(fb, offset, string, attr);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException{
StringBuilder content = new StringBuilder(fb.getDocument().getText(0, fb.getDocument().getLength()));
content.replace(offset, offset + length, text);
if(isValidEndDate(content.toString()))
super.replace(fb, offset, length, text, attrs);
}
boolean isValidEndDate(String endDate){
//check whether endDate is <= startDateField.getText()
}
});