Meaningless Drivel is fun!*
The moose likes Swing / AWT / SWT and the fly likes A textfield that accepts only decimal numbers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "A textfield that accepts only decimal numbers" Watch "A textfield that accepts only decimal numbers" New topic
Author

A textfield that accepts only decimal numbers

Meghna ks
Ranch Hand

Joined: Mar 15, 2001
Posts: 122
Hi
How do I make a textfield to accept only decimal numbers ?!! Any sample/ standard code would help.
Thanks
Meghna
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

The following may not be 100% correct, but I think it is pretty close. Now, if there is a shorter easier way, I hope someone let's us know.





------------------
Happy Coding,
Gregg Bolinger


GenRocket - Experts at Building Test Data
Meghna ks
Ranch Hand

Joined: Mar 15, 2001
Posts: 122
Hi Gregg
Thanks for the response. I tried your piece of code, but the textfield accepts strings also.
I tried this link too and the examples it offers. But the problem is that the textfield accepts strings also. It must be able to accept only numbers comprising a float value. How do I improvise the code in this link to overcome that problem ?!!
http://java.sun.com/docs/books/tutorial/uiswing/components/textfield.html#validation
Thanks
Meghna
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

I'm going to keep looking into that. In the mean time. I figured out how to at least make it accept only numbers and not text. I have

Then, everytime the field loses focus, the code below is called.

Now, the part where I say if (field.getText().compareTo(......, that part is because in my App, it is ok to leave it blank, otherwise it requires a number no matter what unless you never gave the field focus in the first place.
I hope that at least get's you started. I will keep looking into it and if I figure it out, I will let you know.
bye for now.


------------------
Happy Coding,
Gregg Bolinger
Luong Nguyen
Ranch Hand

Joined: May 06, 2001
Posts: 31
Hi,
JTextField's document model can be customized to allow certain forms of input by extending PlainDocument and overriding the insertString() method. The following code shows a class that will only allow digits to be entered. After we can assign this document to a JTextField with setDocument() method.
public class DigitDocument extends PlainDocument {
public void insertString(int off, String str, AttributeSet a) throws BadLocationException {
char[] insChars = str.toCharArray();
boolean valid = true;
for (int i = 0; i < insChars.length; i++) {
if (!Character.isDigit(insChars[i])) {
valid = false;
break;
}
}
if (valid) {
super.insertString(off, str, a);
}
}
}
Regards.
Luong
Meghna ks
Ranch Hand

Joined: Mar 15, 2001
Posts: 122
Hi
Thanks Gregg & Luong
I did find a way out to make the TextField accept only integers. But, the problem is with the decimal numbers. I'm not able to alter my code for the same in overriding the insertString method for the decimal numbers. i did try the code sample Gregg had suggested, but the textfield still accepts Strings & other characters.
I'd really appreciate any help that can follow.
Thanks
Meghna
Matt Hansen
Ranch Hand

Joined: Jul 31, 2001
Posts: 34
What you can do is create a keylistener that will only accept certain characters (in this case numbers or the decimal.) To do this just override the keyTyped method and discard all non-numeric characters.
Example:

Hope this helps.
Paul Stevens
Ranch Hand

Joined: May 17, 2001
Posts: 2823
The Java tutorial has examples of this for JTextField.
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Hi Meghna,
The link to the Java tutorial is provided here.
http://web2.java.sun.com/docs/books/tutorial/uiswing/components/textfield.html#valida tion
Regards,
Manfred.
Ngonidzashe Munyikwa
Greenhorn

Joined: Oct 28, 2011
Posts: 1


Thanks Matt. Worked like a charm. I made a slight modification to your code to make sure One point character alone is entered , the resulting code is below


private void jTextField1(java.awt.event.KeyEvent evt) {

char c = evt.getKeyChar(); // Get the typed character

// Don't ignore backspace or delete
if (c != KeyEvent.VK_BACK_SPACE && c != KeyEvent.VK_DELETE) {
// If the key was not a number then discard it (this is a sloppy way to check)
if (!(c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9')) {

//if point character typed increase numberofpointcharacters by one
if ((c == '.')) {

// If the input string already contains a decimal point, don't
// do anything to it.
if (jTextField1.getText().indexOf(".") < 0)
{
// don't consume it
}
else
{
evt.consume(); // Ignore this key
return;
}

}
else{

evt.consume(); // Ignore this key
}

}
}

}


John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
10 years isn't much time in Ranch
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19656
    
  18

DocumentFilter is the way to go anyway. That code doesn't prevent invalid text being pasted into the text field.

But welcome the Ranch anyway, Ngonidzashe!


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Brian Cole
Author
Ranch Hand

Joined: Sep 20, 2005
Posts: 862
I realize I'm late to this party, but I think using KeyListener for this purpose is a mistake.

There are essentially two correct ways to do this:
  • Use DocumentFilter. Unless your text component is using a custom implementation of Document that doesn't inherit from javax.swing.text.AbstractDocument (which is unlikely) then this is the easiest way, but it's hard to discover because the setDocumentFilter() method is not part of the Document interface. You have to call something like ((AbstractDocument)myTextComponent.getDocument()).setDocumentFilter( myFilter )
  • Make a subclass of a Document type (probably PlainDocument) that rejects the chars you don't want. Set it into your text component either in the constructor or via the setDocument() method.


  • bitguru blog
    Ranganathan Kaliyur Mannar
    Bartender

    Joined: Oct 16, 2003
    Posts: 1076
        
      10

    Brian Cole wrote:
    Make a subclass of a Document type (probably PlainDocument) that rejects the chars you don't want. Set it into your text component either in the constructor or via the setDocument() method.


    This is the method I used to follow. But, DocumentFilter seems to be a better fit.


    Ranga.
    SCJP 1.4, OCMJEA/SCEA 5.0.
     
     
    subject: A textfield that accepts only decimal numbers
     
    Similar Threads
    validation for numbers 1 to 999,999,999
    Assignment
    Double only accurate to 18 significant figures?
    check number
    Text input