• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Restricting input to numbers in the JTextField

 
Khaled Mahmoud
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,

I am using NetBeans 5.0.I want to restrict input only to numbers in a JTextField.So, i have created a class called NumbersDocumentFilter that extends from javax.swing.text.DefaultFilter class.I did override the insertString method in its body it wrote the following line:
throw new java.lang.RuntimeException();

An in the form code :

AbstractDocument portDoc = null;
portDoc = (AbstractDocument) txtPortNumber.getDocument();
portDoc.setDocumentFilter(new NumbersDocumentFilter(5));

No thing happens when the user adds text to the txtPortNumber control.
One strange note :
The netbeans does not recogonize the insertString method i did override as an overriden method from the DocumentFilter class.I have copied the method from the source code of the DocumentFilter class.

Regards,
Khaled Mahmoud
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you only want to accept whole numbers (as I guess is true for a port number), consider using a JSpinner instead.
 
Khaled Mahmoud
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot.
You have saved a lot of work and suffering.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic