-
Restrict the Text in TextFeild
Hi,
Could u tell me a way,where I can restrict the characters to be typed to
4 only in a JTextfield.
I've used the constructor :
JTextField(int columns),but its not working.
Neha.
-
Re: Restrict the Text in TextFeild
You will have to create your own class(Subclass of JTextField) or buy a third
party widget.
Search the JTextField Class code for "insertString in the class comment section.
Mark
"Neha" <cool_sherll@yahoo.com> wrote:
>
>Hi,
>
>Could u tell me a way,where I can restrict the characters to be typed to
>4 only in a JTextfield.
>
>I've used the constructor :
>JTextField(int columns),but its not working.
>
>Neha.
-
Re: Restrict the Text in TextFeild
Hi Neha
Subclass PlainDocument and override the insertString method. Use the following
example
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class Test extends JFrame
{
public Test()
{
JTextField field1 = new JTextField(new LimitDocument(4), "", 20);
JPanel p = new JPanel();
p.add(field1);
getContentPane().add(p, BorderLayout.NORTH);
}
public static void main(String[] args)
{
Test t = new Test();
t.setSize(400, 400);
t.setVisible(true);
}
}
class LimitDocument extends PlainDocument
{
int maxLen;
public LimitDocument(int maxLen)
{
this.maxLen = maxLen;
}
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
{
if(getLength() >= this.maxLen)
{
Toolkit.getDefaultToolkit().beep();
} else
{
super.insertString(offs, str, a);
}
}
}
"Neha" <cool_sherll@yahoo.com> wrote:
>
>Hi,
>
>Could u tell me a way,where I can restrict the characters to be typed to
>4 only in a JTextfield.
>
>I've used the constructor :
>JTextField(int columns),but its not working.
>
>Neha.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks