Restrict the Text in TextFeild


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3

Thread: Restrict the Text in TextFeild

  1. #1
    Neha Guest

    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.

  2. #2
    MarkN Guest

    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.



  3. #3
    Ruchi Dhar Guest

    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
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center