Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A textfield that accepts only decimal numbers

 
Meghna ks
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
How do I make a textfield to accept only decimal numbers ?!! Any sample/ standard code would help.
Thanks
Meghna
 
Gregg Bolinger
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Meghna ks
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 34
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2823
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Java tutorial has examples of this for JTextField.
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
10 years isn't much time in Ranch
 
Rob Spoor
Sheriff
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Brian Cole
Author
Ranch Hand
Posts: 908
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
  •  
    Ranganathan Kaliyur Mannar
    Bartender
    Posts: 1101
    10
    Java Netbeans IDE Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic