Limit number of character in a TextArea

Hi,
how can I limited the number of character in a jTextArea?
thanks!

You have to customize the Document that your text area is using. You can read more about the Document interface here:
http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/text/Document.html
And here is a simple example that demonstrates how you can customize a Document to do what you want. The program should compile and run as is. It will display a JTextArea that only allows ten characters.
import javax.swing.*;
import javax.swing.text.*;
public class LimitedTextArea extends JFrame {
    public LimitedTextArea() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JTextArea text = new JTextArea(5, 40);
        // Set the customized Document on the text area. Only allow
        // a maximum of ten characters:
        text.setDocument(new LimitedDocument(10));
        getContentPane().add(new JScrollPane( text ));
        pack();
        setLocationRelativeTo(null);
    public static void main(String[] args) {
        new LimitedTextArea().setVisible(true);
    // Document that only allows a certain number of characters
    class LimitedDocument extends PlainDocument {
        private int maxLength;
        public LimitedDocument(int maxLength) {
            this.maxLength = maxLength;
        // This method is overriden from the super class. It will be called when
        // you are trying to insert text in your text component (by typing
        // or pasting).
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            int currentLength = getLength();
            if( currentLength >= maxLength ) {
                // There's not room for more characters. Return.
                return;
            if( currentLength + str.length() > maxLength ) {
                // All of the characters we are trying to insert will not fit.
                // We must trim the string.
                str = str.substring(0, maxLength - currentLength);
            // Insert the text:
            super.insertString(offs, str, a);
}

Similar Messages

  • Limit Number of Character Display per Column

    Hello Everyone,
    I am formatting this template. I would like to set a limit for the number of characters that are to be displayed on on a column.
    For example, a column might have 50 characters. and I only want 20 to display. Like the "substr" function.
    Example: a column data is asdfghj12345..and I only want to set for asdfg to be displayed.
    Does anyone know how this can be done?
    Thanks

    Use <?xdofx:substr('myvalue', 1,20)?>
    You can also limit char strings with the word form field option.
    Shreedev

  • To limit number of chracters in textarea.

    hello all,
    please find below a small program to demonstrate how to limit number of charcaters in a textarea.
    i searchedthe forum and i actually got the technique from the forum. but when i put together a sa program it does not work.
    could anyone point out what is the problem in the small piece of code below.
    i am working on jdk 1.2.1
    thanx to all.
    // Example illustrating Limiting number of characters in text area.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class try1 extends JApplet {
    Container contentPane;
    JLabel label;
    JTA1 textarea;
    public void init() {
    // Get the handle on the applet's content pane.
         contentPane = this.getContentPane();
    // Create a text field and add a key listener to it.
         textarea = new JTA1(25);           // of 25 char width
    // Create a button object and register an action listener
         Button button = new Button("Clear");
         button.addActionListener(new ButtonListener());
    // Create a label with the titled border.
         label = new JLabel("Key Typed: NiL");
         label.setBorder(BorderFactory.createTitledBorder
    ("You pressed the Following Key"));
    // Add the text field and button to the applet's content pane.
         contentPane.setLayout(new BorderLayout());
         contentPane.add("North", textarea);
         contentPane.add(label);
         contentPane.add("South", button);
    // Get focus on text field.Note: You can do this only after you add the text field to the container
    class ButtonListener implements ActionListener {     // Create the button listener class.
         public void actionPerformed(ActionEvent e)      {
    // Reset the text components
         textarea.setText("");
    //Return the focus to the text field.
    class JTA1 extends JTextArea
         private int limit;
         public JTA1 ( int limit )
              this.limit = limit;
              addKeyListener( new LimitListener() );     
         class LimitListener extends KeyAdapter
              public void keyPressed( KeyEvent ke )
                   if( getText().trim().length() >= limit )
                   {     ke.consume(); //just consume KeyEvent

    Don't cross post. This question has been answered in your other post.

  • Get the Coordinates of a Character in a TextArea

    Is there a way to determine what the coordinates of a given
    character are in a TextArea control? One project I'm working on
    presents a chunk of text cut off at some number of characters,
    followed by a LinkButton control (e.g., to view "more"), and I'm
    having trouble figuring where to place the LinkButton control
    without knowing the coordinates of the last visible character of
    the TextArea. Anyone dealt with this one before?
    Thanks in advance...
    Chris

    Hm, thanks, but that just places the LinkButton next to the
    TextArea control, beside and outside of it, not "inside" (or really
    over) it, as my example should've implied.
    I think I've found a workable solution -- see below, where
    myCanvas is some Canvas control already defined in MXML somewhere,
    and myText is a Text control already defined (and populated) as
    well:
    var numberOfLines:int =
    myText.mx_internal::getTextField().numLines;
    var lineMetrics:TextLineMetrics =
    myText.getLineMetrics(numberOfLines - 1);
    var targetX:int = lineMetrics.width + 10;
    var targetY:int = (numLines - 1) * lineMetrics.height;
    var myLinkButton:LinkButton = new LinkButton();
    myLinkButton.label = "More...";
    myCanvas.addChild(myLinkButton);
    Still testing, but TextLineMetrics seems to have done the
    trick.
    If anyone has a better approach, let me know! Thanks much.

  • How to limit number of logins per day?

    We have a custom web application (WebAS 6.20) used by people and automated systems. Each user has his own login, and some of these automated systems sometimes produce heavy load because they log into system too often.
    Is there an easy way to:
    1) limit number of logins to, say, 1000 per day and when this limit is reached - do not allow this user to login till midnight
    OR
    2) dedicate one of the processes to the specific user
    thanks in advance

    extend PlainDocument class to restrict the number of characters per line.
    Set this class as model to TextArea.
    Below is a class which does this. May be its useful
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    public class FixedNumericDocument extends PlainDocument {
    private int maxLength = 9999;
    private String max="";
    public FixedNumericDocument(int maxLength) {
    super();
    this.maxLength = maxLength;
    //this is where we'll control all input to our document.
    //If the text that is being entered passes our criteria, then we'll just call
    //super.insertString(...)
    public void insertString(int offset, String str, AttributeSet attr)
    throws BadLocationException {
    if (getLength() + str.length() > maxLength) {
    return;
    else {
    try {
    //check if str is numeric only
    int value = Integer.parseInt(str);
    //if we get here then str contains only numbers
    //chk if it is less than 65535 so that it can be inserted
    super.insertString(offset, str, attr);
    catch(NumberFormatException exp) {
    return;
    return;

  • Are there any plans to fix the misinterpretation of the Exchange ActiveSync policy "Minimum number of character sets"  in IOS6?

    We are testing using IOS6 in our Corporate environment and came across a scenario where IOS6 incorrectly interprets the Exchange 2010 ActiveSync policy "Minimum number of character sets" as the number of special characters required rather than the number of character sets required. Is anyone aware of any plans to correct this in future releases? Here is a thread on Microsoft's forums about the issue:
    http://social.technet.microsoft.com/Forums/en-US/exchangesvrmobility/thread/fe05 1d55-24ba-45e4-b054-67861f28422d/

    We have tried Android, Windows Phone7/8 and they all adhere to the "Minimum number of character sets" set in the ActiveSync policy, but IOS does not.
    Require an alphanumeric password   Select this check box to require device passwords to contain both numbers and letters. The default is numbers only.
    Passwords must include this many character sets   To enhance the security of device passwords, you can require passwords to contain characters from multiple character sets. Select a number from 1 to 4. The sets are letters, uppercase letters, numbers, and symbols. For example, if you select 3, passwords must contain characters from three of these sets.
    All other mobile device except IOS 5.x/6.X don't follow this.
    You have to select "Require an alphanumeric password" which is letters and numbers.  But then you can only select 1-4 for the character sets. 
    So we set it at 1, so that would mean you would only need letters and numbers, IOS does not reconize letters, letters uppercase, numbers or symobols as a charator set, it interprets the setting as how symbols you need.
    If you set it at 2, then IOS makes you have "2" symbols in your password.....and so on...
    Make sense?
    It just seems that IOS does not reconize charator sets, it just looks at the number as how many symbols you need in a password.

  • Are there any plans to fix the misinterpretation of the Exchange ActiveSync policy "Minimum number of character sets"  in IOS5?

    We are testing using IOS5 in our Corporate environment and came across a scenario where IOS5 incorrectly interprets the Exchange 2010 ActiveSync policy "Minimum number of character sets" as the number of special characters required rather than the number of character sets required. Is anyone aware of any plans to correct this in future releases? Here is a thread on Microsoft's forums about the issue:
    http://social.technet.microsoft.com/Forums/en-US/exchangesvrmobility/thread/fe05 1d55-24ba-45e4-b054-67861f28422d/

    Thanks for the responses. I did submit this issue as a bug report earlier this morning also but thought I'd post here in the event any Apple insiders saw this and cared to comment. 
    This really is a significant problem in that our testing shows that the way IOS5 interprets this ActiveSync policy in Exchange 2010 does not allow you to enforce a password using just letters and numbers. This is because  the only valid values for this policy are 1-4. The way IOS5 interprets this requires 1-4 special characters in the password, not 1-4 character sets.

  • Limit Number of Rows on a Page

    Hi all,
    I am unable to succeed with the following.
    I have an XML data source which looks like this:
    <?xml version="1.0"?>
    <LIST_GEMPLOYEES>
    <LIST_G_EMPLOYEE>
    <EMPLOYEE_NUMBER>1</EMPLOYEE_NUMBER>
    <EMPLOYEE_NAME>Employee 1</EMPLOYEE_NAME>
    </LIST_G_EMPLOYEE>
    <LIST_G_EMPLOYEE>
    <EMPLOYEE_NUMBER>2</EMPLOYEE_NUMBER>
    <EMPLOYEE_NAME>Employee 2</EMPLOYEE_NAME>
    </LIST_G_EMPLOYEE>
    <!-- many rows here (LIST_G_EMPLOYEE tags) -->
    </LIST_GEMPLOYEES>
    And I want to define a template which only allows 5 rows on a page.
    What I did:
    I should insert a page break after the limit number of rows on a page is reached. This means that, after each group of 5 rows, a page break should be inserted.
    To accomplish this goal, I followed these steps:
    1. Define a field which will contain and initialize the Counter variable before the table which will show the list of employees, by using the syntax:
    Field1: <?xdoxslt:set_variable($_XDOCTX, ’Counter’, 0)?>
    2. Define the table which list all employees in the data source:
    2.1. Use a 2 columns table. In the first column, define 2 fields as follows:
    2.2. In the second column, define 6 fields containing the following code:
    Field2: <?for-each: LIST_G_EMPLOYEE?>
    Field3: <?EMPLOYEE_NUMBER?>
    Field4: <?xdoxslt:set_variable($_XDOCTX, ’Counter’, xdoxslt: get_variable($_XDOCTX, ’Counter’) + 1)?>
    Field5: <?EMPLOYEE_NAME?>
    Field6: <?if: xdoxslt:get_variable($_XDOCTX, ’Counter’) mod 5=0?>
    Field7: <?split-by-page-break:?>
    Field8: <?end if?>
    Field9: <?end for-each?>
    Here is explanation for syntax I used:
    Field1: Declare and init Counter variable to value = 0
    Field2: This fetches through all employees - start a for-each cycle
    Field3: This prints the employee number
    Field4: This increments the Counter variable
    Field5: This prints the employee name
    Field6: This tests whether Counter variable is divided by 5
    Field7: This generates a page break
    Field8: End of condition
    Field9: End of for-each cycle
    Result:
    The first page has just the header and the second page has the header and only record and it goes the same
    for the rest of the pages. Any help is greatly appreciated.
    Thanks.

    Have a look at this post
    http://winrichman.blogspot.com/2008/09/limit-row-per-page.html

  • Assigning large number if character to a Codepage

    Do  we have a tool / process  which can assign large number of character to a code page, which cannot be done by SAP SPUM4. There are 18 languages and 10 code pages.
    Languages listed below,
    French,English,German,Italian,Spanish,Portuguese,Bulgarian,Japanese,Chinese,Danish,Russian,Dutch,Finnish,Malaysian,Czech,Hungarian,Norwegian,Swedish
    we run SPUM4 in our Development Environment and found 450.000 words without a language associated. This corresponds to 2,5 months of movements from our ERP  productive clients. After applying a dictionary and language patterns provided by SAP, we have now 274.000 words left (and 150.000 duplicates).  I need to find other ways to decrease this number so that I end up with a workable list of words.

    There is no method but assigning them more or less manually or using hints.
    You may check for special characters in languages, e. g. the polish ł will be displayed as ³ when you login in English - although this may also be a different character.
    We had the same "problem" with 8 languages (including more than one Asian language) so it was cumbersome.
    Markus

  • Limit number of concurrent connection

    is there a way for me to limit the number of concurrent
    connections to the media server. my upload bandwitdh is about a meg
    so having too many connections just kills the whole thing. i would
    like to put a limit at 5 connections. is there a way to do
    this?

    well i am only using flash media server to displaying videos
    and just that. the reason i went with media server vs. progressive
    was fullscreen method. since flash doesn't natively support
    fullscreen you have to open another browser in fullscreen with
    javascript. the problem with that is it start loading from
    beginning so i decided to go server that way it only has to buffer
    and get to the same point without having to load the whole video up
    to that point. Now i want to limit number people that can be
    watching the video. if i get more that 5 connection the whole thing
    slows down. i am not too familiar with server based connections so
    i don't know how to limit the number concurrent connections.

  • URL length has crossed the limit of 1800 Character Size

    a)How to Confirm if Department User request were hitting Oracle Application Server HTTP Protocol or not and URL length has crossed the limit of 1800 Character Size

    My Question is if URL length has crossed the limit of 1800 Character Size will Department User request will hit Oracle Application Server HTTP Protocol or not .If yes how to check that if not then how to verify that.

  • Limit number for new field

    Hello there
    Anybody know what is the limit number for new field in each record type?
    My client wants me to create about 200 new fields in Account record type.
    Is it possible to do so?

    Hi, You can refer this
    https://secure-ausomxdsa.crmondemand.com/docs/1.10.0.1080.0.00/enu/help/CustomFieldHelp.html
    -- Venky CRMIT

  • Limit number of recipients send out external once

    Hi all,
    I have Exchange server 2013 CU7, I want to limit number of recipients when my users send email to external/internet.
    For example:
    If my users send email to more than 50 external recipients once, they will receive error "bla bla"
    Limitation is not apply when my users send email to internal recipients"
    or external sender send email to internal recipients
    How can I do it ? (which send connector , receive connector , transport config , transport service , transport server)
    Thank for your help.
    Jack

    Hi Jack,
    Thank you for your question.
    I agree with Bruce.
    I am sorry that we could not meet your requirement that the limit of recipient is just for external/Internet.
    When we configure those setting, it will be worked for all recipient(including internal or external). It was referred by the following link:
    https://technet.microsoft.com/en-us/library/bb310760%28v=exchg.141%29.aspx
    If there are any questions regarding this issue, please be free to let me know. 
    Best Regard,
    Jim
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact [email protected]
    Jim Xu
    TechNet Community Support

  • Which method to count the number of character in a string?

    Hi all,
    I want to know which class and method to count the number of character in a string?
    Gary

    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html

  • Get number of character within a String by number of pixels

    How can i get the number of character within a String
    by a width value...
    for example..
    i have a String = "1234567890abcdefghi.........."
    and when i give the width "10"
    i will get the String "12".
    or the number of charcter..
    or somthingggggggggggggggg
    please help..
    Shay

    i solved this...
    by doing somthing similar..
    i made a for loop on all character
    and evrey time i am get a sub string from the 0 till the loop index..
    and i am chashing the last string
    so when a sub width is greater the the requested width
    i am returning the lst cashed result
    thanks.. all..

Maybe you are looking for

  • Error in installing OID PatchSet (OID9022) - Urgent..

    Currently, i try to install the OID9022 patchset in infrastructure instance. So, i try to run patch.sh %./patch.sh SHUTDOWN ALL THE OID Processes SHUTDOWN THE LISTENER *** Important *** This patch should be installed on OID 9.0.2.1.0 only Do you want

  • Plugins NOT working in Logic 8

    Here, the following 3rd party plugins are not working properly in Logic 8: - VSL Performance Tool v. 1.1 - NI Kontakt Player 2 v. 2.2.3

  • Help me with this "training" feature - leopard differences?

    Hi there - I'm an experienced macophile but confused about "training mode" regarding junk mail. I've searched mail help and this forum for answers but without luck. Everything seems to be working fine, and frankly I haven't paid much attention to the

  • Corrupt? No files, but memory is used?

    When i go into "music" or "videos" on my ipod there are no files, but the memory is still used up (21gb used 9gb left)!! I think my ipod files are corrupt, is there any way of getting them back? "un-corrupting" them?? Also i had to recently clear my

  • CCX 7.0(1) HA - can't see personnal configuration in Desktop Admin

    Hi, I have CCX 7 with HA, with desktop administrator I can't see the personnal configuration menu, the only way to see that is with the web interface of Desktop admin. In desktop admin I can see Call center 1, Workflow config, but not the personnal c