Date formatter field with built in method testing

In FoxPro and other languages, you can assign a data object as a date field.  That field has its own built in method for testing the user input.  You can also set the type of date easy with one command as set date US or British etc.  However, I cannot do this assignment in Java programming code with such simple commands.  How can you assign the date field to do its own built in method for testing the user input?  Is there a command where you can set the date to the country?
Vanavah EdwardsAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

for_yanCommented:

Date format is a function onot of the country but of the locale:
See this code from:

http://stackoverflow.com/questions/8050405/dateformat-with-country-locales-issue

import java.text.DateFormat;
import java.util.Locale;
import java.util.Date;

public class DateFormatTest {
  public static void main(String args[]){
    Locale[] locales={new Locale("de_AT"),new Locale("de_DE"), new Locale("de"), new Locale("en_US"), new Locale("en"), new Locale("fr_FR"), new Locale("fr_CA"), new Locale("fr")};
    Date today= new Date();
    for(Locale l: locales){
        System.out.println(l.toString()+"\t"+
              DateFormat.getDateInstance(DateFormat.DEFAULT,l).format(today)+"\t"+
              DateFormat.getDateInstance(DateFormat.FULL,l).format(today));
    }
  }
}

Open in new window

0
Vanavah EdwardsAuthor Commented:
How does this enable the date field to test the user input
0
for_yanCommented:
import java.text.DateFormat;
import java.util.Locale;
import java.util.Date;

public class DateFormatTest {
  public static void main(String args[]){

      String myDateString = "Tuesday, November 8, 2011";

    Locale[] locales={new Locale("de_AT"),new Locale("de_DE"), new Locale("de"), new Locale("en_US"), new Locale("en"), new Locale("fr_FR"), new Locale("fr_CA"), new Locale("fr")};
    Date today= new Date();
    for(Locale l: locales){
      //  System.out.println(l.toString()+"\t"+
       //       DateFormat.getDateInstance(DateFormat.DEFAULT,l).format(today)+"\t"+
       //       DateFormat.getDateInstance(DateFormat.FULL,l).format(today));

        DateFormat df = DateFormat.getDateInstance(DateFormat.FULL,l);
        df.setLenient(false);
        boolean goodDate = false;
          java.util.Date  dd = null;
        try{
          dd = df.parse(myDateString);
            goodDate = true;
        }catch(Exception ex){
               goodDate = false;
        }

          if(dd == null || !goodDate){
              System.out.println("this string is bad for locale " + l);
          }    else  {
                  System.out.println("this string is good for locale " + l);
          }

        
    }
  }
}

Open in new window


Output:
this string is good for locale de_at
this string is good for locale de_de
this string is bad for locale de
this string is good for locale en_us
this string is good for locale en
this string is good for locale fr_fr
this string is good for locale fr_ca
this string is bad for locale fr

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

Vanavah EdwardsAuthor Commented:
I will consider this tomorrow its now 1:30am
0
CEHJCommented:
You're probably thinking of something like this:

http://www.java2s.com/Code/Java/Swing-JFC/DifferentconfigurationsofJFormattedTextFieldDate.htm

However, a much better way of dealing with this is to use a date picker, which will prevent incorrect entry in the first place

http://www.toedter.com/en/jcalendar/
0
Vanavah EdwardsAuthor Commented:
I did not explain myself properly.  I forgot I have a date textfield "sodate" already created in a basic Java program.  The date text field  "sodate" does do all the validation test itself properly.  If I enter a wrong date it prevents me from going to the next field, when I press enter .  However, if I press tab or arrow down it accepts the wrong date, changes it more wrongly, and goes to the next field.
0
CEHJCommented:
Sounds like even more reason to use a date picker as i suggested.

If it's buggy, and they're not your bugs, then there's probably not much you can do about it. It's probably worth posting your code though
0
Vanavah EdwardsAuthor Commented:
Sorry, I forgot to attache my date field assignment Java Code
// My Date field assignment
Calendar cal = Calendar.getInstance();
Format dateformat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
sodate = new JFormattedTextField(dateformat);
sodate.setValue(new Date());

Open in new window

0
CEHJCommented:
Perhaps try
sodate.setFocusLostBehavior(JFormattedTextField.COMMIT_OR_REVERT);

Open in new window

0
Vanavah EdwardsAuthor Commented:
I am still getting the same problem.  Is there a particular argument that can be set in the method or a method.
0
CEHJCommented:
Have a look at the other integer options available (See javadoc)

http://docs.oracle.com/javase/6/docs/api/javax/swing/JFormattedTextField.html
0
Vanavah EdwardsAuthor Commented:
Your suggest may work may be I am entering it the wrong way.
0
Vanavah EdwardsAuthor Commented:
I did what you suggeest.  I copied out your code and paste it in mines with a few modifications.  It now validates.  However, if I enter say the month as 32 it changes to the current month 12 and goes to the nesx field.   I would prefer it to remain at the same field to allow me to put in a correct month and then go to the next field when I press go.  Can you do this?
// Date field assignment
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
JFormattedTextField sodate = new JFormattedTextField(df);
sodate.setValue(new Date());
df.setLenient(false);
boolean goodDate = false;
java.util.Date  dd = null;
try{
       dd = df.parse("sodate");
       goodDate = true;
   }catch(Exception ex){
       goodDate = false;
   }

Open in new window

0
CEHJCommented:
As i mentioned, see the api docs. The following, with the code that follows, should fulfill your needs:

"JFormattedTextField allows the focus to leave, even if the currently edited value is invalid. To lock the focus down while the JFormattedTextField is an invalid edit state you can attach an InputVerifier. The following code snippet shows a potential implementation of such an InputVerifier:"
0
for_yanCommented:
Strange. I think I added setLenient(false) - the behavior you describe would be if setLenient is true
0
Vanavah EdwardsAuthor Commented:
How would you lock the focus down by using the InputVerifier.  You forgot to include the snippet code.
0
CEHJCommented:
It's in the api docs:


public class FormattedTextFieldVerifier extends InputVerifier {
     public boolean verify(JComponent input) {
         if (input instanceof JFormattedTextField) {
             JFormattedTextField ftf = (JFormattedTextField)input;
             AbstractFormatter formatter = ftf.getFormatter();
             if (formatter != null) {
                 String text = ftf.getText();
                 try {
                      formatter.stringToValue(text);
                      return true;
                  } catch (ParseException pe) {
                      return false;
                  }
              }
          }
          return true;
      }
      public boolean shouldYieldFocus(JComponent input) {
          return verify(input);
      }
  }

Open in new window

0
Vanavah EdwardsAuthor Commented:
I would like to use your snippet code but I don't understand how I can integrate it with mine. I have given my code earlier.  The earlier solution by the expert entitle "for van" works very well except it doesn't stay on the current field to allow the user to put in the right month or day but changes it.  How can your code be integrated with this or  you suggesting a completely new set of codes.
0
Vanavah EdwardsAuthor Commented:
I tried the change to true as was suggest earlier by the "for van" expert but that changes the user input totally wrong by itself and goes to the next field
0
for_yanCommented:
you can use the action listener and then check the input and if it is bad setFocuis baclk on your textbox. They would need to make a carriage return though to trigger that action which may be a problem
You can also use KeyListener but then the oroblem is whether they finished the input
0
for_yanCommented:
You nrmally still validate all inoput fileds when tou submit the whole form
0
Vanavah EdwardsAuthor Commented:
FOR CEHJ
How can I incorporate your snippet with my code so as to make what I have already done by expert "for van" perfect or how can I incorporate you new solution in my code.
0
CEHJCommented:
>>How can I incorporate your snippet with my code

I don't really see the problem. You'd just do
sodate.setInputVerifier(new FormattedTextFieldVerifier());

Open in new window

0
Vanavah EdwardsAuthor Commented:
I copied and paste sodate.setInputVerifier(new FormattedTextFieldVerifier());   But I am getting an error "FormattedTextFieldVerifier cannot be resolved to a type".   I also paste it at different lines but all inserts gave the same error.  How should this be incorporated?
0
Vanavah EdwardsAuthor Commented:
Your method for the data formatter works satisfactory.  I never heard back from the CEHJ expert.  If in the future you came across code to enable the cursor to remain on the same field and not change the date to the current date and go to the next field please email me immediately.  Also if you have a separate method that can be incorporated as a separate class that I can call please email me immedaitely.
0
for_yanCommented:
No, I don't think I know anything right away - i in most cases in Java applications
I check at the next general event - like submission of the whiole form or something

In my mind it is rather difficult because of what I write above - with text boxes - actionListener
filres on cariage return and not all users will use it, and keyistener fires each keystroke - but then
you have a hard time understanding that user finished the input

One option - if you have many boxes - you may have keyListeners on all of them and once user
was typing in one of them and then switched to another one - you may assume that user
finished typing in the previous box - did not try it myself, it may have some annoying effects for users either

You may also try to use FocusListener - so that when your component loses keyboard focus
you may do the checking of waht was entered there - didn't try that but it may work

In my sutuation - just collecting all boxes and checking all when user prsees submity button more or leess
worked in Java application, because  applications are not like web pages - you do not need to deal
with loading the page again or something - so this is not very burdensome

0
for_yanCommented:
You may look at this code which has two textboxes
and forces the user to have a string "good" witihin
the first textbox using FocusListener.
It is still rather painful, and I'm not sure users will enjoy it.
So I still believe validation after user's "major" action
would be more appropriate

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class FocusListenerTry extends JFrame implements FocusListener, KeyListener 
{

    private JTextField goodTry;

    int countEvents = 0;

    public FocusListenerTry() {
         JPanel panel;
          JTextField dummy;
        panel = new JPanel();
        goodTry = new JTextField(10);
        dummy = new JTextField(10);
            goodTry.addFocusListener(this);
          goodTry.addKeyListener(this);
         dummy.addKeyListener(this);

        panel.setLayout(new FlowLayout());

        panel.add(goodTry);
         panel.add(dummy);

        Container c = this.getContentPane();
        c.add(panel);
        
        this.setSize(150,100);
        this.setLocation(300,300);
        this.setVisible(true);




    }


   public void focusGained(FocusEvent fe) {
                   


   }
     public void focusLost(FocusEvent fe) {
         if(countEvents > 0)return;
             goodTry.removeFocusListener(this);
         if(fe.getSource().equals(goodTry)){
             countEvents++;
               if(goodTry.getText().trim().length() == 0)return;

             String text = goodTry.getText().trim();

             if(text.indexOf("good") == -1){
                 System.out.println("Not good - try again!");


                JOptionPane.showMessageDialog(this, "Not good - try again!");

                 goodTry.requestFocus();


                               return;

             }  else {
                 countEvents = 0;
             }
         }

   }



    public void keyReleased(KeyEvent ke){

    }

     public void keyTyped(KeyEvent ke){
        

         

            if(ke.getSource().equals(goodTry)){
                 if(goodTry.getText().trim().length() == 0)return;
                countEvents = 0;
                 goodTry.addFocusListener(this);
          }

    }

      public void keyPressed(KeyEvent ke){
            if(!(ke.getSource().equals(goodTry)) && countEvents > 0)   {
                                JOptionPane.showMessageDialog(this, "Not good - try again!");
            }


    }



    public static void main(String[] args) {
        new FocusListenerTry();
    }

}

Open in new window

0
for_yanCommented:
please, don't post your questions in the old trails - we are generating unneccssary email traffic with that

I'll show you how to validate date in the format mm/dd/yy
0
for_yanCommented:
This is date validation:

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
public class DateValidation {
  
public static boolean validateDate(String inputDate){

          SimpleDateFormat sdf100 = new SimpleDateFormat("MM/dd/yy");
        sdf100.setLenient(false);

     

                java.util.Date dd100 = null;
             boolean goodDate = false;

           try{

         dd100 = sdf100.parse(inputDate, new ParsePosition(0));
                goodDate = true;

           } catch(Exception ex){
                goodDate = false;

           }
         if(dd100 != null && goodDate)return true;
        else return false;

    }


    public static void main(String[] args) {





        SimpleDateFormat sdf100 = new SimpleDateFormat("MM/dd/yy");
        sdf100.setLenient(false);

     

       if(validateDate("25/99/99")){
          System.out.println("25/99/99  is good date!");
        }   else
        {
             System.out.println("25/99/99  is bad date!");
        }


              if(validateDate("12/13/99")){
          System.out.println("12/13/99  is good date!");
        }   else
        {
             System.out.println("12/13/99  is bad date!");
        }

                  if(validateDate("abcd")){
          System.out.println("abcd  is good date!");
        }   else
        {
             System.out.println("abcd  is bad date!");
        }

}
}

Open in new window


Output:
25/99/99  is bad date!
12/13/99  is good date!
abcd  is bad date!

Open in new window

0
CEHJCommented:
Sorry vanavah, but i fail to see what the accepted answer has to do with the focus/validation behaviour of a gui component ..?
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.