tags:

views:

834

answers:

6

Is there any way to accept only numeric values in a JTextField? Is there any special method for this?

A: 

numberField = new JFormattedTextField(NumberFormat.getInstance());

Formatted text field tutorial

Stefan Kendall
A: 

You would like to take a look at JFormattedTextField

Formatted text fields provide a way for developers to specify the valid set of characters that can be typed in a text field

This is a subclass of JTextField, so you can use it like this:

JTextField textField = new JFormattedTextField(NumberFormat.getInstance());
OscarRyz
A: 

Look at JFormattedTextField.

Zed
+3  A: 

Although there is the pure evil JFormattedTextField there isn't a trivial way to do it using only the Swing library. The best way to implement this sort of feature is with a DocumentFilter.

Some code I prepared earlier. A bit of description.

Tom Hawtin - tackline
Maybe a more straightforward example of the using Document to filter the input:http://www.java2s.com/Code/Java/Swing-JFC/Textfieldonlyacceptsnumbers.htm
Thimmayya
+1 for noting the evilness of JFormattedTextField
banjollity
I'm curious about @Tom and @banjollity's comments on the evilness of JTextField. So, related question:Why is JFormattedTextField evil?
kwutchak
Link to the question: http://stackoverflow.com/questions/1320117/why-is-jformattedtextfield-evil
kwutchak
A: 

I think it is the best solution:

JTextField textField = new JFormattedTextField(new MaskFormatter("###")); //
Michal
A: 

You can create a beautiful text field in java that accepts or allows only numeric values.. You can even set the precision for the float values... check the code in zybocodes(www.zybonics.com/zybocodes/ http://www.zybonics.com/zybocodes/code/CodeViewForm.php?codeID=3

Chris