Java JFormattedTextField for typing dates - java

I've been having trouble to make a JFormattedTextField to use dates with the format dd/MM/yyyy. Specifically, as the user types, the cursor should "jump" the slashes, and get directly to the next number position.
Also, the JFormattedTextField must verify if the date entered is valid, and reject it somehow if the date is invalid, or "correct it" to a valid date, such as if the user input "13" as month, set it as "01" and add +1 to the year.
I tried using a mask ("##/##/####") with the validate() method of JFormattedTextField to check if the date is valid, but it appears that those two don't work well together (or I'm too green on Java to know how... :), and then the user can type anything on the field.
Any help is really appreciated! Thanks!

try using JCalendar

You may have to use a regular JTextField and call setDocument() with a custom document. I recommend extending PlainDocument, this makes it easy to validate input as the document changes, and add slashes as appropriate.

Related

TextView inputType date in Android - how does it work?

I have not found this in any documentation, tutorial or question. Pretty much all tutorials concerned date picker, so I am confused about its functionality.
I have TextView with inputType="date". How do I handle it? Does actually it do anything other than text field does?
What are best practices?
It only has set/get methods for String type. Am I right in assumption that I have to parse contents manually? And if putting in default value, having to format it myself too?
Is there any definition of expected date format? Does it handle Locale differences (mm/dd/yyyy in some, dd/mm/yyyy in other)?
Is there any validation?
Or is it basically "do it yourself" type thing without much convenience?
input type date means it will open numeric virtual keyboard on the screen when the user tap the textview. To parse it to your required format, you have to use JAVA date time class.
Input type simply specifies which kind of keyboard you want the user to use, to simplify the input. For example, a phone number input field does not require letters. Yes, you have to manually parse it, or use helper classes as stated by Mark Henry.
Textview - inputType

Parse any string to Sql date

I wonder if it's possible to parse any string (at least to try) to sql Date without specifing the string format? In other words I want to make a generic method who take as input a string and return an sql Date.
For instance I have:
String date1="31/12/2099";
String date2="31-12-2099";
and call parseToSqlDate(date1) and parseToSqlDate(date2) which will returns sql dates.
Short answer: No
Why: Parsing any string to a valid date is a task you as an intelligent being could not do (there is no "logical" way to determine the correct date), so you cannot "tell" a computer(program) to do that for you (see JGrice's comment, and there we still have 4-digit years).
Long answer: Maybe, if you are willed to either take risks or do not need a high rate of success.
How:
Define your minimal (format) requirements of a date. E.g. "a minimal date contains 1-8 numbers; 01/01/2001 , 01-01-01 , 01.01 (+current year) , 1.1 (+current year), 1 (+current month + current year) and/or "..contains 1-6 numbers and the letters for months"; 01-Jan-2001 and so on.
Split the input along any non-number/non-month-name characters, with a regex like [^0-9a-zA-Z] (quick thought, may hold some pitfalls)
You now have 1 to 3 (actually more if e.g. the time is included) separate numbers + 1 month name which can be aligned for year/month/day any way you like
For this "alignment", there are several possibilities:
Try a fixed format at first, if it "fits", take it, else try another (or fail)
(only of you get more than one entry at a time) guess the format by assuming all entries have the same (e.g. any number block containing values > 12 is not a month and > 31 is not a day)
BUT, and this is a big one, you can expect any such method to become a major PITA at some point, because you can never fully "trust" it to guess correctly (you can never be sure to have missed some special format or introduced some ambiguous interpretation). I outlined some cases/format, but definitely not all of them, so you will refine that method very often if you actually use it.
Appendix to your comment: "May be to add another parameter and in this way to know where goes day , month and so on?" So you are willed to add "pseudo-format-string" parameter specifying the order of day, month and year; that would make it a lot easier (as "simply" filtering out the delimiters can be achieved).

How to restrict inputs in jtextfield strictly to double values?

I am coding a gui and I wanted to use JFormattedTextField to verify my Input as double value, but the amountFormatter does not give me the right input I typed in back. So I tried to create an own Formatter with ("##########") which gives me a number with 10 digits, BUT i cannot verify double values(because they usually have a '.' in it)...
So my question is: How to simply verify double Values with Jformatted TextFields, or is there a much easier way with another Swing Component?
UPDATE
Thx for your great answers!!! But is there possibly a solution with JFormatted TextField?
this is basic reason for why JFormattedTextField is there,
set proper number formatter for JFormattedTextField, and /or with Locale too
possible for JSpinner and JFormmatedTextField too
EDIT
you can start with
NumberFormat format = NumberFormat.getNumberInstance();
format.setGroupingUsed(false);
format.setGroupingUsed(true);// or add the group chars to the filter
format.setMaximumIntegerDigits(10);
format.setMaximumFractionDigits(2);
format.setMinimumFractionDigits(5);
format.setRoundingMode(RoundingMode.HALF_UP);
I've implemented number fields based on JFormattedTextField.
They also support a min and a max value.
Maybe you find them useful (the library is open source):
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JRealNumberField.html
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JDoubleField.html
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JFloatField.html
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JLocalizedRealNumberField.html
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JLocalizedDoubleField.html
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JLocalizedFloatField.html
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JWholeNumberField.html
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JByteField.html
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JIntegerField.html
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JLongField.html
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JShortField.html
Tutorial:
http://softsmithy.sourceforge.net/lib/docs/tutorial/swing/number/index.html
More info:
http://puces-blog.blogspot.ch/2012/07/news-from-software-smithy-version-02.html
Homepage:
http://www.softsmithy.org
Download:
http://sourceforge.net/projects/softsmithy/files/softsmithy/
Maven:
<dependency>
<groupId>org.softsmithy.lib</groupId>
<artifactId>softsmithy-lib-core</artifactId>
<version>0.2</version>
</dependency>

SimpleDateFormat localized month names

I have searched throughout the site but I think I have a slightly different issue and could really do with some help before I either have heart failure or burn the computer.
I dynamically generate a list of month names (in the form June 2011, July 2011) and obviously I want this to be locale sensitive: hence I use the simple date format object as follows:
//the actual locale name is dependent on UI selection
Locale localeObject=new Locale("pl");
// intended to return full month name - in local language.
DateFormat dtFormat = new SimpleDateFormat("MMMM yyyy",localeObject);
//this bit just sets up a calendar (used for other bits but here to illustrate the issue
String systemTimeZoneName = "GMT";
TimeZone systemTimeZone=TimeZone.getTimeZone(systemTimeZoneName);
Calendar mCal = new GregorianCalendar(systemTimeZone); //"gmt" time
mCal.getTime(); //current date and time
but if I do this:
String value=dtFormat.format(mCal.getTime());
this "should" return the localized version of the month name. In polish the word "September" is "Wrzesień" -- note the accent on the n. However all I get back is "Wrzesie?"
What am I doing wrong?
Thanks to all - I accept now that it's a presentation issue - but how can I "read" the result from dtFormat safely - I added some comments below ref using getBytes etc. - this worked in other situations, I just can't seem to get access to the string result without messing it up
-- FINAL Edit; for anyone that comes accross this issue
The answer was on BalusC's blog : http://balusc.blogspot.com/2009/05/unicode-how-to-get-characters-right.html#DevelopmentEnvironment
Basically the DTformat object was returning UTF-8 and was being automatically transformed back to the system default character set when I read it into a string
so this code worked for me
new String(dtFormat.format(mCal.getTime()).getBytes("UTF-8"),"ISO-8859-1");
thank you very much for the assistance
Your problem has nothing to do with SimpleDateFormat - you're just doing the wrong thing with the result.
You haven't told us what you're doing with the string afterwards - how you're displaying it in the UI - but that's the problem. You can see that it's fetching a localized string; it's only the display of the accented character which is causing a problem. You would see exactly the same thing if you had a string constant in there containing the same accented character.
I suggest you check all the encodings used throughout your app if it's a web app, or check the font you're displaying the string in if it's a console or Swing app.
If you examine the string in the debugger I'm sure you'll see it's got exactly the right characters - it's just how they're getting to the user which is the problem.
In my tests, dtFormat.format(mCal.getTime()) returns
październik 2011
new SimpleDateFormat(0,0,localeObject).format(mCal.getTime()) returns:
poniedziałek, 3 październik 2011 14:26:53 EDT

Can a Double be formatted without scientific notation?

I am aware of the various posts floating out there with regards to the same issue.
Mine its a little bit different and it might be a little obvious, but I will need your comments.
I am currently using Hibernate Search and Lucene to Index entity properties.
I have a bunch of Double properties on my entities.
These entities using the default Bridges from Lucene (Bridge i.e the one in charge converting LongToString and StringToLong) are giving me troubles once the scientific notation starts to be used.
I am trying to show on DataTables on a .xhtml Credit and Debit amounts, their lenght can be as long as 18 digits, and their DataBase (DB2) type is BIGINT.
I can not change the DataBase type
to Long for example.
I can not change either the Double
type attributes of my entities
either to for example Long
So whats the question?
Is there a way from a String say "1234567890" to retrieve a Double whose format is 1234567890 and not 1.23456789E9 as it is being done by default by Double.parseDouble(FormattedString)?
PD: I am aware of the existance of DecimalFormat, however take into account using this formater will give me a String formated correctly say : "#######.E0" but what I really need is a Double with such format, however when doing Double.parseDouble(FormattedString) I will loose such format.
Hope I was clear and thanks for any help.
Is there a way from a String say "1234567890" to retrieve a Double whose value is 1234567890 and not 1.23456789E9 as it is being done by default by Double.parseDouble(FormattedString)?
Your question doesn't really make sense. 1234567890 is the same value as 1.23456789E9 and a double represents one of them, if and only if it also represents the other.
I am aware of the existance of DecimalFormat, however take into account using this formater will give me a String formated correctly say : "#######.E0" but what I really need is a Double with such format, however when doing Double.parseDouble(FormatedString) I will loose such format.
No, there is no way to construct a Double so that it is displayed in a certain way. The toString method for Double is what it is, and it can't be changed.
The only thing you can do is to for instance use DecimalFormat or String.format but as you've noted, you'll always end up with a String.
Don't know nothing of Lucene, but you can never have a Double in a .xhtml Document it is always a characterstring. A Double doesn't have a Format, only a String representation of a Double has.
So I finally got the solution to my problem.
After rounding up what aioobe and Jens Schauder said. I am able to format the text dynamically on my .xhtml with the following tag:
<h:outputText value="#{recordTable[column.property]}"
rendered="#{column.header ne 'Details' and
column.header eq ('Total Credit Amount' or
'Total Debit Amount')}">
<f:convertNumber pattern="########"/>
</h:outputText>
Thanks for making clear to me these basic stuff I had blurred :)

Categories