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>
Related
I've tried coming up with a solution to this problem by combining a few separate issues other people posted on this site, but somehow can't get it right.
I receive a BigDecimal from the server which I need to display in a TextBox inside a GWT page.
BigDecimal bigDec = new BigDecimal(type.mb3.toString()).setScale(2, BigDecimal.ROUND_HALF_UP);
t12.setText(bigDec.toString());
After this call the TextBox displays ex. 1200.00, which is the correct value, however I would like for it to be formatted with a German locale ##0,00.
I can't convert it by specifying the format via NumberFormat, as it doesn't accept BigDecimal. Is there another way I can format this without writing a neanderthal "if you see dot exchange it for comma" text parser?
The comment Thomas Broyer provided was the answer. I needed to use java.lang.Number instead of pure BigDecimal and it formatted correctly.
I used JFormattedTextField withNumberFormat in this way:
-Creat a JFormattedTextField refernce
JFormattedTextField integerField;
-Create a NumberFormat refernce
NumberFormat integerFieldFormatter;
-In the constructor:
integerFieldFormatter = NumberFormat.getIntegerInstance();
integerFieldFormatter.setMaximumFractionDigits(0);
integerField = new JFormattedTextField(integerFieldFormatter );
integerField.setColumns(5);
..........
I meant to use it with integer numbers only, but when I type numbers like 1500 it is converted after losing focus to 1,500 , and exception thrown this is the first line of it:
Exception in thread "AWT-EventQueue-0"
java.lang.NumberFormatException: For input string: "1,500"
When I use JTextField instead of JFormattedTextField All integers accepted normally, But the reason why I want to use JFormattedTextField is to benefit from its input restriction advantages.
I realize this is an old question but I just stumbled upon it through the same issue. As the other answers seemed like workarounds to me, I took a closer look at the NumberFormat methods.
I found that the easiest approach would actually be to simply deactivate grouping on the NumberFormat instance:
NumberFormat integerFieldFormatter = NumberFormat.getIntegerInstance();
integerFieldFormatter.setGroupingUsed(false);
That way no group delimiters will appear in the textfield output.
Of course you will also not be able to use them for your input, but that was not intended by the question, right?
Also for an integer instance of NumberFormat you don't need to explicitly setMaximumFractionDigits(0), as that is part of what getIntegerInstance() does for you.
I discovered the solution to my problem; Here it is:
The exact problem is that when I use JFormattedTextField with NumberFormat, the JFormattedTextField adds comma ',' before any next 3 digits for example
1000 rendered as 1,000
10000 rendered as 10,000
1000000 rendered as 1,000,000
When I read an integer value from JFormattedTextField usign this line of code
int intValue = Integer.parseInt(integerField.getText());
The comma is read as part of the string; 1000 read as 1,000 and this string value cannot be converted to integer value, and so exception is thrown.
Honestly the solution is in this Answer but I will repeat it here
use str.replaceAll(",","")
int intValue = Integer.parseInt(integerField.getText().replaceAll(",", ""));
This will replace any comma charachter ',' in the returned string and will be converted normally to int as expected.
Regards
You can do it in (at least) 2 ways:
Using a keyListener
Using DocumentFilter
if you want to use KeyListener:
KeyListener listener = new KeyAdapter(){
public void keyTyped(KeyEvent e){
if(e.getKeyCode()<KeyEvent.VK_0||e.getKeyCode()>KeyEvent.VK_9{//input<'0' or input>'9'?
e.consume();//delete the typed char
}
}
}
yourTextField.addKeyListener(listener);
to use the DocumentFilter check this link: How to allow introducing only digits in jTextField?
EDIT: i forgot to say this. As MadProgrammer said in the first comment to this answer, KeyListener is not the proper way to do it, because
You do not know in what order KeyListeners will be notified of the event and the key may have already gone to the text component before it reaches you (or it could have been consumed before it reaches you)
EDIT #2: ANOTHER QUICK WAY
MaskFormatter formatter = new MaskFormatter("#####");
JFormattedTextField field = new JFormattedTextField(formatter);
And the trick should be done. with this you can insert up to 5 digits in tour textfield, more '#' in the string parameter for the formatter = more digits can be typed by the user
Try this, This is a complete solution for creating and validating number JTextField
NumberFormat format = NumberFormat.getInstance();
format.setGroupingUsed(false);//Remove comma from number greater than 4 digit
NumberFormatter sleepFormatter = new NumberFormatter(format);
sleepFormatter.setValueClass(Integer.class);
sleepFormatter.setMinimum(0);
sleepFormatter.setMaximum(3600);
sleepFormatter.setAllowsInvalid(false);
sleepFormatter.setCommitsOnValidEdit(true);// committ value on each keystroke instead of focus lost
JFormattedTextField textFieldSleep = new JFormattedTextField(sleepFormatter);
textFieldSleep.setText("0");
I'm a beginner in Java, and NetBeans. I'm trying to make a simple program where you introduce 2 numbers and their sum gets divided by two. However, I'm using JFormattedTExtFields and I don't know how to customize the allowed input in them. Basically I'm trying to find out how to:
Only allow numbers to be entered in JFormmatedTextField;
Only allow a certain amount of numbers;
You could use a NumberFormat and specify the maximum number of integer digits with setMaximumIntegerDigits.
Here's a nice article.
Basically you can do something like:
NumberFormat f = NumberFormat.getNumberInstance();
f.setMaximumIntegerDigits(maxDigitsAmount);
JFormattedTextField field = new JFormattedTextField(f);
The Format should guarantee that the inserted String satisfy the format. Anyway even if a number is supplied, the textfield will store it as a String. So if you need your original Integer you need to rebuild it like suggested #noise:
Integer i = Integer.toString(field.getText());
Hello and thank you in advance for the help.
I am having some trouble formatting using a Java function to mark up a price in HTML.
It seems that, no matter what I do, I cannot insert custom content between the numbers and the decimal (throws Illegal Argument Exception). Is there any known way to achieve the following:
NumberFormat nf = getNumberFormat("'<span class=\"dollars\">'##'</span></span class=\"decimal\">'.'</span></span class=\"cents\">'00'</span>'", locale);
nf.format(number);
Assume locale and number are correctly initialized.
If you look at the docs for DecimalFormat you'll see that they talk about the prefix and the suffix text - but not putting arbitrary text within a number.
It sounds like you should basically write this bit of formatting yourself - possibly using DecimalFormat for each section of the number.
You might consider using String.format(String pattern, Object... arguments). You can pass your simply formatted numbers as arguments.
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.