You will want to use a DocumentFilter
to filter the input coming into the text field.
Check out MDP's Examples which actually has an example of the question you are asking
Frage
I have a jtext field
when user type a number like
123456789,10
it will automatic set in jtextfield
123,456,789.10
then if user click a button it will
System.out.print( the_same_number );
that will result
123456789.10
(should i use formatted field in this case?)
thanks..
Lösung
You will want to use a DocumentFilter
to filter the input coming into the text field.
Check out MDP's Examples which actually has an example of the question you are asking
Andere Tipps
You can opt for the DocumentFilter
as suggested by @MadProgrammer. However, it will be difficult to tackle the requirement to have a different display in the text field and when printing to console (it will require some extra manual parsing/formatting).
Combined with the requirement to accept only numbers I would strongly suggest to look at the JFormattedTextField
in combination with a NumberFormat
.
JFormattedTextField
will only accept input that can be parsed by the NumberFormat
(you can type invalid input, but it will never be accepted)JFormattedTextField#getValue
) will be a Double
(if you choose the correct format), so you can print it perfectlyNote that the standard JFormattedTextField
has some usability issues. With a bit of googling you can find different improved version of the JFormattedTextField
. For example this one where I find the only missing thing is visual feedback when the input is invalid (e.g. make the background red)
"how to make jtextfield only accept input number and dot (.) and coma (,)?"
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if ((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == 46 || e.KeyChar == 44){
}
else{
}
}