This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes Restricting input to numbers in the JTextField 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 "Restricting input to numbers in the JTextField" Watch "Restricting input to numbers in the JTextField" New topic
Author

Restricting input to numbers in the JTextField

Khaled Mahmoud
Ranch Hand

Joined: Jul 15, 2006
Posts: 361
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


SCJP, SCJD,SCWCD,SCDJWS,SCEA 5 MCP-C#, MCP-ASP.NET - http://www.khaledinho.com/
Life is the biggest school
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
If you only want to accept whole numbers (as I guess is true for a port number), consider using a JSpinner instead.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Khaled Mahmoud
Ranch Hand

Joined: Jul 15, 2006
Posts: 361
Thanks a lot.
You have saved a lot of work and suffering.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Restricting input to numbers in the JTextField
 
Similar Threads
setEditable and blinking cursor
Reg. Validatin JTextFields
How to show arabic and arabic in a JTextBox when user enter the numbers?
Is It Possible To Set Input Numbers for JTextFiled?
Using DocumentFilter