0

I'm coding in Java using Netbeans IDE.

I want to make a limitation for a jFormattedTextField.

There are two jFormattedTextFields. One is Start Date(date1). Other is End Date(date2). Now I want to limit the minimum date to the "End Date". If some one types 2015-07-07 as a Start Date, it must restrict to give past days (2015-07-06,05,04 days).

Hasan Dulanga
  • 73
  • 1
  • 11
  • I think JFormattedTextField will not handle this, but check [this](http://stackoverflow.com/questions/2592501/how-to-compare-dates-in-java) out – m.cekiera Jul 09 '15 at 19:18
  • @m.cekiera oh.... Firstly thank you for you reply sir. It is no problem ,if there is a way to do this by a jTextField too.I just used jformattedtextfields as I do not want to code the limitation for the date format. Do you have a method for jTextField sir..? – Hasan Dulanga Jul 09 '15 at 19:38
  • 3
    1. see AbstractFormatter, I'm sure that I'm posted here a few times for number, 2. job exactly for JSpinner with SpinnerDateModel :-) – mKorbel Jul 09 '15 at 19:59
  • You want to make the earlier date the end date? That's backwards from convention. – Gilbert Le Blanc Jul 10 '15 at 16:40

1 Answers1

0

use DocumentFilter to add validation:

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()
    }
});
Santhosh Kumar Tekuri
  • 3,012
  • 22
  • 22