How to set jFormattedTextField so it only allows 2 numbers? - java

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());

Related

How to dynamically change card number input mask (Android, Java)

I need to change input mask dynamically. For example, if user inputs 13 digits then one mask, if 20 then another.
I am using redmadrobot:inputmask. Here is my code
ArrayList<String> affineFormats = new ArrayList<>();
affineFormats.add("[0000] [000] [000] [000]");
affineFormats.add("[0000] [0000] [0000] [0000] [0000]");
String format = "[0000] [000] [000] [000]";
MaskedTextChangedListener listener = new PolyMaskTextChangedListener(
format,
affineFormats,
true,
etCardNumber,
null,
new MaskedTextChangedListener.ValueListener() {
#Override
public void onTextChanged(boolean b, String s) {
//here some code
}
});
etCardNumber.addTextChangedListener(listener);
But when I enter the card number is used the last one added is formatted according to affineFormats. Please help me fix this problem.
From your code it looks like you are using a slightly outdated version of our library.
In v.4 we already have PolyMaskTextChangedListener merged with the MaskedTextChangedListener. We also introduced a handy utility called AffinityCalculationStrategy, which might actually help with your problem.
From our Wiki:
Affinity calculation strategy
Affinity is an integer number, which represents the similarity between the input and the current mask. Thus, the mask with the highest affinity is picked to format the output.
Affinity calculation strategy is a text field listener property allowing to alter the math behind the affinity calculation.
...
AffinityCalculationStrategy.EXTRACTED_VALUE_CAPACITY— this strategy comes in handy when the mask format radically changes depending on the extracted value length.
(and your digits are the extracted value)

How display currency with Freemarker when using Longs

So let's say I have:
class Person
{
private long salary;
}
Where 5345273 would be equal to $53,452.73 (in other words the last two digits are the cents.
Is there a way to directly reference ${Person.salary} so that it displays the proper amount?
I did see that there are pre-defined formats such as Currency but there doesn't appear to be one if you use longs. I did see it was possible to create your own custom formatter but is this the only way? And if so is there anyone who already created one because I can't imagine I'm the only person using long to manage currency amounts. And also is that the correct solution?
Should be possible to convert the long to a double in the expression. Something like this: ${(Person.salary/100)?string.currency}

How to make JFormattedTextField accept integer without decimal point (comma)?

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");

How to print upto two decimal places in java using string builder?

hi i am trying to print after dividing in string builder and printing that string builder let show me my code ,
string.append("Memomry usage:total:"+totalMemory/1024/1024+
"Mb-used:"+usageMemory/1024/1024+
" Mb("+Percentage+"%)-free:"+freeMemory/1024/1024+
" Mb("+Percentagefree+"%)");
in above code "totalmemory" and "freememory" is of double type having bytes value in point not null so i divide it by "1024" two times to get it in "Mb" and "string" is variable of string builder after using this code i am simply printing it a am getting result as shown below,
Used Memory:Memomry usage:
total:13.3125Mb-used:0.22920989990234375Mb (0.017217645063086855%)
-free:13.083290100097656Mb (0.9827823549369131%)
i want to get percentage in twodecimal place and values of used and free memory in mb like this "used:2345.25" in this pattren remember
Hopes for your suggestions
Thanks in Advance
How about String.format()?
System.out.println(String.format("output: %.2f", 123.456));
Output:
output: 123.46
Try like this
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
Using DecimalFormat, we can format the way we wanted to see.
You can use DecimalFormat to print out to two decimal places. So, to print x = 2345.2512 with two decimal places, you would write
NumberFormat f = new DecimalFormat("#.00");
System.out.println(f.format(x));
which will print 2345.25.
Even though it is possible to use NumberFormat and it's subclass DecimalFormat for this issue,
these classes provide a lot of functionality that may not be required for your application.
If the objective is just pretty printing, I would recommend using the format function of the String class. For your specific code it would look like this:
string.append(String.format("Memomry usage:total:%1.2f Mb-used:%1.2f Mb(%1.2f %%)-free:%1.2f Mb(%1.2f %%)",totalMemory/1024/1024,usageMemory/1024/1024,Percentage,freeMemory/1024/1024,Percentagefree));
If you are intending to specify a standard format in which all numbers are represented irrespective of whether they are being parsed from strings or formatted to strings, then I would recommend using singletons of the *Format classes. They allow you to use standard formats and also to pass format descriptions between methods.
Hope that helps you select the right method to use in your application.

Inserting custom String between number and decimal - Java DecimalFormat

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.

Categories