Limit the no. of char in the JTextfield

I want to limit the number charecters in the JTextfield during the time of typing the charecters. How can I do it simply ? One way, I can make an own class extend the JTextfield and check by using the events to restrict the charecters. Other than this simply how can I do it ?
advance thanx
Goban

Here's an simple and easy solution using PlainDocument. It gives a beep sound if the user tries to enter text after the specified length.
textField.setDocument( new TextFieldVerifier() );
class TextFieldVerifier extends PlainDocument {
int requiredLength = 10; // whatever length you want
public void insertString( int offset, String str, AttributeSet attSet ) throws BadLocationException {
boolean valid = true;
if (str == null) {
return;
String old = getText( 0, getLength() );
/* insert the new string at the given offset, into the old string */
String newStr = old.substring( 0, offset ) + str + old.substring( offset );
if (newStr.length() > requiredLength)
valid = false;
Toolkit.getDefaultToolkit().beep();
if ( valid )
super.insertString( offset, str, attSet );
}

Similar Messages

  • How to limit the number of characters entered in a JTextfield???

    Hello there,
    I have created a Text box using swing component JTextField and I want to limit the number of characters entered to 8 characters..how do i proceed with that?
    Thanks in advance!
    Joe

    Ty out this
    import com.sun.java.swing.text.*;
    //import javax.swing.text.*;
    public class JTextFieldLimit extends PlainDocument {
    private int limit;
    // optional uppercase conversion
    private boolean toUppercase = false;
    JTextFieldLimit(int limit) {
    super();
    this.limit = limit;
    JTextFieldLimit(int limit, boolean upper) {
    super();
    this.limit = limit;
    toUppercase = upper;
    public void insertString
    (int offset, String str, AttributeSet attr)
    throws BadLocationException {
    if (str == null) return;
    if ((getLength() + str.length()) <= limit) {
    if (toUppercase) str = str.toUpperCase();
    super.insertString(offset, str, attr);
    import java.awt.*;
    import com.sun.java.swing.*;
    //import javax.swing.*;
    public class tswing extends JApplet{
    JTextField textfield1;
    JLabel label1;
    public void init() {
    getContentPane().setLayout(new FlowLayout());
    label1 = new JLabel("max 10 chars");
    textfield1 = new JTextField(15);
    getContentPane().add(label1);
    getContentPane().add(textfield1);
    textfield1.setDocument
    (new JTextFieldLimit(10));

  • How can i limit the user to enter only A to Z and space in JFormattedText

    dear
    i want to use JFormatedTextField in two manners
    1.Limit the no of charecters.means in a text field only 20 charecters r allowed.
    2.and also check the enterd charecter must be a to z and space not other chareters r allowed.
    3.same for numbers means 0 to 9 and decimal.
    how can i do by using the JFormated TextFilef.

    Probably lacks in some cases but what the hell.
    * Filename:           JSMaskedTextField.java
    * Creation date:      22-mei-2004
    * Author:                Kevin Pors
    package jsupport.swingext;
    import java.awt.event.KeyEvent;
    import java.util.Arrays;
    import javax.swing.JTextField;
    * A masked textfield is a textfield which allows only a specific mask of
    * characters to be typed. If characters typed do not occur in the mask
    * provided, the typed character will not be 'written' at all. The default mask
    * for this <code>JSMaskedTextField</code> is <code>MASK_ALPHA_NUMERIC</code>
    * @author Kevin Pors
    * @version 1.32
    public class JSMaskedTextField extends JTextField {
        /** Masking for alphabetical lowercase characters only. */
        public static final String MASK_ALPHA_LCASE = "abcdefghijklmnopqrstuvwxyz ";
        /** Masking for alpha-numeric characters (lcase/ucase) only. */
        public static final String MASK_ALPHA_NUMERIC = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
        /** Masking for alphabetical uppercase characters only. */
        public static final String MASK_ALPHA_UCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
        /** Masking for numbers only. */
        public static final String MASK_NUMERIC = "0123456789";
        /** Masking for hexadecimals. */
        public static final String MASK_HEXADECIMAL = "0123456789ABCDEF";
         * An array of keyevent constants defining which keys are always to be
         * allowed, no matter what.
        private final int[] ALWAYS_ALLOWED = new int[] { KeyEvent.VK_BACK_SPACE,
                KeyEvent.VK_DELETE, KeyEvent.VK_UP, KeyEvent.VK_DOWN,
                KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT, KeyEvent.VK_SHIFT,
                KeyEvent.VK_HOME, KeyEvent.VK_END};
        /** Boolean specifying whether casing should be ignored. */
        private boolean ignoringCase = true;
        /** Specifying whether the maskin is enabled */
        private boolean isMaskingEnabled = true;
        /** The mask for the textfield. */
        private String mask = MASK_ALPHA_NUMERIC;
         * Creates a default number field.
        public JSMaskedTextField() {
            super(null, null, 0);
            Arrays.sort(ALWAYS_ALLOWED);
         * Creates a number field, with a specified number of columns.
         * @param columns The columnnumber.
        public JSMaskedTextField(int columns) {
            super(null, null, columns);
            Arrays.sort(ALWAYS_ALLOWED);
         * Creates a JSMaskedTextField with a masking.
         * @param mask The masking to be used.
        public JSMaskedTextField(String mask) {
            super(null, null, 0);
            Arrays.sort(ALWAYS_ALLOWED);
            setMask(mask);
         * Gets the masking for this masked textfield.
         * @return Returns the mask.
        public String getMask() {
            return this.mask;
         * Gets whether this JSMaskedTextField should be ignoring casing.
         * @return Returns if the component should be ignoring casing.
        public boolean isIgnoringCase() {
            return this.ignoringCase;
         * Checks whether masking is enabled. Default should be true.
         * @return Returns true if masking is enabled, false if not.
        public boolean isMaskingEnabled() {
            return this.isMaskingEnabled;
         * Sets whether it should be ignoring casing when checking for alpha-chars.
         * @param ignoringCase The ignoringCase to set.
        public void setIgnoringCase(boolean ignoringCase) {
            this.ignoringCase = ignoringCase;
         * Sets the masking for this textfield. The masking will determine which
         * characters can be typed. If the characters in de <code>mask</code> do
         * not occur in the typed character, it won't be typed.
         * @param mask The mask to set.
        public void setMask(String mask) {
            this.mask = mask;
         * Sets the masking enabled. If <code>false</code> this component will
         * behave just like a normal textfield.
         * @param isMaskingEnabled true if masking should be enabled.
        public void setMaskingEnabled(boolean isMaskingEnabled) {
            this.isMaskingEnabled = isMaskingEnabled;
         * Sets text of this textfield. If the blah blah.
         * @see javax.swing.text.JTextComponent#setText(java.lang.String)
        public void setText(String text) {
            for (int i = 0; i < text.length(); i++) {
                if (getMask().indexOf(text.charAt(i)) < 0) { // does not occur
                    return;
            super.setText(text);
         * @see javax.swing.JComponent#processKeyEvent(java.awt.event.KeyEvent)
        protected void processKeyEvent(KeyEvent e) {
            if (!isMaskingEnabled()) {
                return;
            char typed = e.getKeyChar();
            int code = e.getKeyCode();
            for (int i = 0; i < ALWAYS_ALLOWED.length; i++) {
                if (ALWAYS_ALLOWED[i] == code) {
                    super.processKeyEvent(e);
                    return;
            if (typed == KeyEvent.VK_BACK_SPACE) {
                super.processKeyEvent(e);
            if (isIgnoringCase()) {
                String tString = new String(typed + "");
                String ucase = tString.toUpperCase();
                String lcase = tString.toLowerCase();
                if (getMask().indexOf(ucase) < 0 || getMask().indexOf(lcase) < 0) {
                    e.consume();
                } else {
                    super.processKeyEvent(e);
                    return;
            } else { // not ignoring casing
                if (getMask().indexOf(typed) < 0) {
                    e.consume();
                } else {
                    super.processKeyEvent(e);
    }

  • There si any trouble when I input Chinese to the JTextField in Applet.

    There si any trouble when I input Chinese to the JTextField in Applet.

    thanks for your help,
    my tool is form builder,
    my form version is 10.1.2.0.2
    and the field is set to CHAR ,
    when i run an easy form
    and switch the input method to chinese,
    there is no input window,the focus directly be in field, even doesn't complete input a Chinese character,
    in usually ,when switch the input to chinese,the focus will be in field when complete input a Chinese character
    i Try to do it in version is 9.0, there isn't wrong As above
    any one can tell me how to resolve it ,thanks

  • How to limit the size in a cell belonging to a JTable

    We are handeling a JTable control and we've just realized we aren't able to capture the focuslost event in this control. Hence, We want to know how we can advise the user when he has written more character than are allowed.

    here jr. Look at this...
    //Prior to J2SE 1.4, limiting the capacity of a text component involved overriding
    //the insertString() method of the component's model. Here's an example:
        JTextComponent textComp = new JTextField();
        textComp.setDocument(new FixedSizePlainDocument(10));
        class FixedSizePlainDocument extends PlainDocument {
            int maxSize;
            public FixedSizePlainDocument(int limit) {
                maxSize = limit;
            public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
                if ((getLength() + str.length()) <= maxSize) {
                    super.insertString(offs, str, a);
                } else {
                    throw new BadLocationException("Insertion exceeds max size of document", offs);
    //J2SE 1.4 allows the ability to filter all editing operations on a text component.
    //Here's an example that uses the new filtering capability to limit the capacity of the text component:
        JTextComponent textComponent = new JTextField();
        AbstractDocument doc = (AbstractDocument)textComponent.getDocument();
        doc.setDocumentFilter(new FixedSizeFilter(10));
        class FixedSizeFilter extends DocumentFilter {
            int maxSize;
            // limit is the maximum number of characters allowed.
            public FixedSizeFilter(int limit) {
                maxSize = limit;
            // This method is called when characters are inserted into the document
            public void insertString(DocumentFilter.FilterBypass fb, int offset, String str,
                    AttributeSet attr) throws BadLocationException {
                replace(fb, offset, 0, str, attr);
            // This method is called when characters in the document are replace with other characters
            public void replace(DocumentFilter.FilterBypass fb, int offset, int length,
                    String str, AttributeSet attrs) throws BadLocationException {
                int newLength = fb.getDocument().getLength()-length+str.length();
                if (newLength <= maxSize) {
                    fb.replace(offset, length, str, attrs);
                } else {
                    throw new BadLocationException("New characters exceeds max size of document", offset);
        }

  • How can I limit the number of attempts to print a web page

    Hi I'm trying to find a resolution for an issue on our network.
    We run several kiosk machines that allow customers to print out documents and web pages. However we are finding that we waste a lot of ink due to user's frequently sending the same print task to the printers.
    Just yesterday we had someone print out over 70 pages because they just keep clicking print.
    I've tried looking for an add-on that would address this but was not able to find one.
    My question is this, Is there an internal setting that can be changed in firefox to limit the number of print attempts to say once every 30 seconds, or even a way to make a dialogue box come on screen saying that the print request is currently processing and not allow more printing until the current task is completed.

    Sorry, there is no setting within Firefox to prevent that from happening. Once the user sees the "native print dialog" box (what is seen when you do Ctrl + P to initiate printing), the operating system and the printer drivers take it from there.
    I have seen something similar to that on kiosk / rental PC's in FedEx Office stores, that notify the user of the cost per page the user wants to send to a printer, and if the user should happen to click again to print the same pages again it asked if you want to spend another $x.xx to print a second copy. Wouldn't be too much different to just shut off the printing of multiple copies of the same document and notify the user of that action.
    My advice is to discuss that with whoever set up those kiosks to being with.

  • Limit the number of open production order

    Dear PP experts,
    I am working on discrete scenario where client want to limit the number of open production order per work center. The more elaboration is like, for one work center the only specific number of production should remain open (e.g. 5 production order in assembly shop) when user is trying to open 6th production order system should restrict that.
    Does any standard functionality available in system or needs development?
    Regards,
    Shekhar

    Dear,
    You can do it with avilability check for materail and capacity.
    In OPJK do the for your production order type as no release if materail and capacity i missing.
    Hope clear to you.
    Regards,
    R.Brahmankar

  • How do I apply filters or limit the rows on my report using a Date field in SQL report builder 3.0?

    I have a status of completed and a date field in the dataset. The date field is either empty or contains a date. All 2015 dates are holding dates.
    So how can I limit the report to only pull completed status with an empty date or a holding date?
    I have not been able to set an OR option on a date field filter and if I add two filters on the date column one for empty one for > 12/31/2014 then it treats it as an "and" and pulls nothing from the list I have in sharepoint.
    any help will be appreciated.

    Hi MB,
    In Reporting Services, the relationship of  filters is “And”, and there is no option to change the relationship from “And” to “Or”. While we can use “or” operator within the expression to create one filter to integrated all filters to work around this
    issue.
    We can add a filter as follows in the dataset to limit the rows in your report:
    Expression: =Fields!date.Value is nothing or Fields!date.Value>"12/31/2014"    Type: Boolean
    Operator: =
    Value: true
    If there are any other questions, please feel free to ask.
    Thanks,
    Katherine Xiong
    If you have any feedback on our support, please click
    here.
    Katherine Xiong
    TechNet Community Support

  • How to  limit the access of a transaction

    please provide hw to create an authorization object... like hw to limit the access of a particular userdefined trasaction to a particular user

    hi
    good
    Element of the authorization concept.
    Authorization objects allow you to define complex authorizations.
    An authorization object groups together up to 10 authorization fields in an AND relationship in order to check whether a user is allowed to perform a certain action.
    To pass an authorization test for an object, the user must satisfy the authorization check for each field in the object.
    http://help.sap.com/saphelp_nw04s/helpdata/en/52/671285439b11d1896f0000e8322d00/content.htm
    Basic form->
    AUTHORITY-CHECK OBJECT object
    ID name1 FIELD f1
    ID name2 FIELD f2
    ID name10 FIELD f10.
    Example
    Check whether the user is authorized for a particular plant. In this case, the following authorization object applies:
    Table OBJ : Definition of authorization object
    M_EINF_WRK
    ACTVT
    WERKS
    Here, M_EINF_WRK is the object name, whilst ACTVT and WERKS are authorization fields. For example, a user with the authorizations
    M_EINF_WRK_BERECH1
    ACTVT 01-03
    WERKS 0001-0003 .
    can display and change plants within the Purchasing and Materials Management areas.
    Such a user would thus pass the checks
    AUTHORITY-CHECK OBJECT 'M_EINF_WRK'
        ID 'WERKS' FIELD '0002'
        ID 'ACTVT' FIELD '02'.
    AUTHORITY-CHECK OBJECT 'M_EINF_WRK'
        ID 'WERKS' DUMMY
        ID 'ACTVT' FIELD '01':
    but would fail the check
    AUTHORITY-CHECK OBJECT 'M_EINF_WRK'
        ID 'WERKS' FIELD '0005'
        ID 'ACTVT' FIELD '04'.
    To suppress unnecessary authorization checks or to carry out checks before the user has entered all the values, use DUMMY - as in this example. You can confirm the authorization later with another AUTHORITY-CHECK .
    thanks
    mrutyun

  • How to limit the number of rows in a report

    I have several reports with a number of parameters - date ranges etc.
    Depending on the parameter values selected by the user the reports can return thousands of rows.
    I would like to limit the number of rows returned to, say, 500. If more than 500 rows are returned by the query then display an error message requesting that the user enter more specific parameters.
    Ideally for performance reasons it would be good to catch the error before the datafile is generated, but I don't know if this is possible. Alternatively a check in the template might do the job - using COUNT on the group?.

    Hi Hugh,
    In your query, you got to add rowum < 500 or some sort of DB specific limit to the row being returned,
    this will help to stop the report to get more than 500 records and the report template wont have any restriction.
    or
    you can do that in template too, but i would not recommend.
    In these both cases or in any case, you cannot give any meaningful error if it exceeds N rows,there is no option like this till now.

  • How can I limit the number of emails retained on my ipad air?

    How can I limit the number of emails that are retained on my iPad Air?  Because of legal requirements of a long-term project, I cannot permanently delete emails relating to that project from my ISP's mail server.  My gmail account contains over 17,000 emails and, upon setting up my new iPad, and updating to ios 7.1.1, I now have all 17,000+ emails taking up space.  I would like to limit the emails by count as I was able to do on my old iPad running ios 5.1.1 OR to retain them based on date range.  I have not found any instructions on the support discussions or general iPad blogs that allow me to do that.  Any way around this problem?
    I also miss the 5.1.1 mail search feature that allowed me to narrow the search by from/to/subject/all.  Does anyone know if that feature is available using some little-known ios 7.1.1 feature?
    Thanks for your help.

    jlfcba wrote:
    IOS 7.1.1 doesn't show a "days to sync" parameter anywhere in SETTINGS/Mail,Contacts,Calendars/ACCOUNTS/GMAIL Account/ GMAIL Acccount Info.  There is nothing in iTunes relating to such an option either.  So, it seems I'm back to square one.
    If you have a decent mail provider like Microsoft Hotmail or Outlook.com mail it does.
    If you have Gmail it does not.  Quite right. Gmail is rubbish.

  • How Can I limit the bandwith of my internet connection on linux?

    Hello, I have 2 Pc's, one for my brother, and the other for me. And well, always we have problems about downloads and lags when we are playing.
    For example, when I download packages from pacman, it is done at maximum speed "eating" all connection, and my brother has lag.
    Is there anyway to limit the bandwith that use my programs to half, for example? If maximum download speed is 100KB/s, pacman only can download 50 KB/s maximum.
    Greetings

    Depending on your router you may be able to set Ingress Rate Limit under QoS. Also have a look into trickle: http://aur.archlinux.org/packages.php?d … s=0&SeB=nd
    http://monkey.org/~marius/pages/?page=trickle
    Last edited by somairotevoli (2007-07-21 01:42:55)

  • HT2729 I have limited space on my new ipad. How can I limit the number of songs from my itunes on my imac from going to my ipad when I connect the two?

    I have limited space on my new ipad. How can I limit the number of songs from my itunes on my imac from going to my ipad when I connect the two?

    you can do this by keeping the external hard drive connected and doing the following
    -hold shift key down on computer while opening iTunes and a prompt will appear to choose a library
    -select choose library, iTunes should bring up your explorer windows where you can search for the external HD
    -after you find the external HD find the iTunes folder you just copied to it
    -after opening the iTunes folder look for the file that says iTunes library.itl or if you can't see that extenstion just look for a document looking thing in the iTunes folder that shows up as a database file
    -double click the database file and boom iTunes should load your library without having to copy it to the computer
    PS: do make sure that if you are going to do it this way, make sure that the external HD is connected at all times, because if you don't then you will get exclamation marks next to your iTunes songs
    double PS: if you are unsure how to find out if the iTunes library file is a database file just right click it and choose properties and under the type it should say database file
    hope this helps:)

  • Hi, how can I limit the number of emails I can see on my iPhone 5. Every time in delete one and older email gets added from my live.co.uk account (where I want to keep my 2500 emails) I just don't want many on my phone. Thanks

    Hi, how can I limit the number of emails I can see on my iPhone 5. Every time in delete one and older email gets added from my live.co.uk account (where I want to keep my 2500 emails) I just don't want many on my phone. Thanks

    You can't. Why on earth would you attempt to manage 2500 emails with setting up a folder structure or some means of doing so? Simply keeping them in an single inbox is not realistic, no matter what email client you use.

  • How can I limit the number of messages coming into my email accounts on the IOS7

    I don't like the new IOS7 system most annoying is the excess battery useage and need to recharge the other is I can no longer limit the number of emails that are in my cell's email accounts old system let you choose the amount of messages. 
    already did the basic things to eliminate battery drainiage getting rid of open pages which was also annoying to figure out how to use as you can't simply click and hold then delete all open apps running in the back ground you must touch and slide them off the phone. I don't let apps do auto updates.
    They need to do something about the battery and having to have all emails on the phone which likely is sucking up space.
    Any suggestions?

    I don't think it matters what you use as your email client. This is a feature that existed before and was missed in the upgrade to IOS 7. I read on another post that if you contact Apple support they just tell you to report it in Apple feedback.  I just submitted feedback at http://www.apple.com/feedback/  I couldn't find an IOS section to post it to, so I just posted it in the iPhone section. Maybe if enough people do this, Apple will fix it.

Maybe you are looking for

  • Purchase order data base

    I need help. I have a database that contains all purchase orders I'd like to be able to create a report that shows only the most recent order for each supplier ordered by date.  Sounds simple but I have been struggling with this for awhile. Thanks

  • Transaction timeout? [solved]

    Hi, I am getting an time out when deploying a BPEL process: java.sql.SQLException: javax.resource.ResourceException: RollbackException: Transaktionen er markeret til tilbagestilling: Timed out I have found several posts regarding change the timeout v

  • HP Laptop brand new 99 windows 8 updates won't download

     I am helping a lady I work with with her HP Laptop.  She forgot her password so I have her laptop and I restored the system. Windows 8 has 99 updates that will not download.  At least I do not think they are downloading, the bar just moves for 5 min

  • Expired beta Boot Camp questions

    My 1.2 beta version Boot Camp has expired. Holding down the option key during reboot, I still see the Windows partition as a startup option but attempting to boot into it results in a black screen (no message, no sound). I assume that's the result I

  • Status reporting

    Hello, Did anyone designed a queries on status reporting. I encountered a few problems when tried to build a query. I think I did not defined something. I generated a virtual Info Provider for status reporting - SEMBCSV11. Also the following info obj