How to limit number of characters in a JTextField?

Hi,
I am new to java and I would like to create a JTextField which only allows the users to enter no more than 32 characters. How do I do that? I am looking for a "set..." function but cannot find it.
Thanks for any hint.
Richard

Unfortunately there's no setXXX() method that will do it. You'll need to create a new document class that will accomplish what you want. See attached sample working code.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class Limit {
public static void main(String args[]) {
  new LimitFrame();
class LimitFrame extends JFrame {
JTextField jtf = new JTextField(10);
LimitFrame() {
  super();
  jtf.setDocument(new LimitDocument(5));
  /* Components should be added to the container's content pane */
  Container cp = getContentPane();
  cp.add(BorderLayout.NORTH,jtf);
  /* Add the window listener */
  addWindowListener(new WindowAdapter() {
   public void windowClosing(WindowEvent evt) {
    dispose(); System.exit(0);}});
  /* Size the frame */
  pack();
  /* Center the frame */
  Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
  Rectangle frameDim = getBounds();
  setLocation((screenDim.width - frameDim.width) / 2,(screenDim.height - frameDim.height) / 2);
  /* Show the frame */
  setVisible(true);
class LimitDocument extends PlainDocument
int limit;
public LimitDocument(int limit)
  this.limit = limit;
public void insertString(int offset, String s, AttributeSet a) throws BadLocationException
  if (offset + s.length() <= limit)
   super.insertString(offset,s,a);
  else
   Toolkit.getDefaultToolkit().beep();
}

Similar Messages

  • How do I limit number of characters in a JTextField?(different from others)

    Hi,
    I know this question has been posted several times on this forum, but my question is actually a different one. So please read.
    I have the following code that puts two JTextFields in a JFrame. I want to limit the number of characters in the first JTextField to three characters. What's different about my question from other solutions provided, is that I don't want to be able to type more than three characters in the JTextField, and then not be able to get out of JTextField unless I have three or less characters. What I do want, is to have maximum of three characters, not be able to type the fourth, and have access to the other JTextField at all times.
    I have tried the following solution of setting an InputVerifier to my JTextField, but it hasn't worked, since I can still type the fourth character.
    Looking forward to your help!
    Thanks.
    import java.awt.Dimension;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import javax.swing.InputVerifier;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class TextFieldVerifier {
         public TextFieldVerifier()
              JFrame frame = new JFrame("My TextVerifier");
              JPanel panel = new JPanel();
              JLabel firstTextFieldLabel = new JLabel("First: ");
              JLabel secondTextFieldLabel = new JLabel("Second: ");
              final JTextField myTextField = new JTextField();
              myTextField.setPreferredSize(new Dimension(100,20));
              myTextField.setInputVerifier(new InputVerifier()
                   public boolean verify(JComponent input) {
                        if(myTextField.getText().length()<=3)
                             return true;
                        else
                            return false;     
              myTextField.addKeyListener(new KeyAdapter()
                   public void keyTyped(KeyEvent e)
                        if(!myTextField.getInputVerifier().verify(myTextField))
                             myTextField.setText(myTextField.getText().substring(0, myTextField.getText().length()-1));
              JTextField secondTextField = new JTextField();
              secondTextField.setPreferredSize(new Dimension(100,20));
              panel.add(firstTextFieldLabel);
              panel.add(myTextField);
              panel.add(secondTextFieldLabel);
              panel.add(secondTextField);
              frame.getContentPane().add(panel);
              frame.setSize(new Dimension(200,100));
              frame.setVisible(true);
         public static void main (String [] args)
              TextFieldVerifier v = new TextFieldVerifier();
    }

    Thanks, JayDS! Your suggestion worked. And I've come up with the following code with help of your suggestion. However, I'm not happy with the fact that I see empty spaces in my JFormattedTextField when I don't have anything entered in it, or when my textfield has focus and I click it again. Also, I'd like the text alignment to always stay on the right, even if I have less than 3 digits.
    Could you please help me out with that?
    Thanks!
    import java.awt.Dimension;
    import java.text.ParseException;
    import javax.swing.JFormattedTextField;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.text.MaskFormatter;
    public class TextFieldVerifier {
         public TextFieldVerifier()
              JFrame frame = new JFrame("My TextVerifier");
              JPanel panel = new JPanel();
              JLabel firstTextFieldLabel = new JLabel("First: ");
              JLabel secondTextFieldLabel = new JLabel("Second: ");
              try{
                   VariableLengthMaskFormatter formatter = new VariableLengthMaskFormatter("###");
                   final JFormattedTextField myTextField = new JFormattedTextField(formatter);
                   myTextField.setHorizontalAlignment(JTextField.RIGHT);
                   myTextField.setPreferredSize(new Dimension(100,20));
                   panel.add(firstTextFieldLabel);
                   panel.add(myTextField);
              } catch (ParseException ex) {
                   ex.printStackTrace();
              JTextField secondTextField = new JTextField();
              secondTextField.setPreferredSize(new Dimension(100,20));
              panel.add(secondTextFieldLabel);
              panel.add(secondTextField);
              frame.getContentPane().add(panel);
              frame.setSize(new Dimension(200,100));
              frame.setVisible(true);
         protected MaskFormatter createFormatter(String s) {
             MaskFormatter formatter = null;
             try {
                  formatter = new MaskFormatter(s);
             } catch (java.text.ParseException exc) {
                 System.err.println("formatter is bad: " + exc.getMessage());
                 System.exit(-1);
             return formatter;
         public static void main (String [] args)
              TextFieldVerifier v = new TextFieldVerifier();
    }Edited by: programmer_girl on Mar 10, 2008 11:10 PM

  • Limit number of characters in a JTextField

    Now I know that this question has been asked very often but the answers that have been given do not always work. According to other posts you can either use a KeyListener or a DocumentListener. The problem with the code that I have seen using a KeyListener is that you can't use the backspace key when the limit is reached. I am using a JTextField and all the answers dealing with Documents use a JTextArea and I can't figure out how to get it to work with JTextField. I don't understand why the Swing package just didn't come out with a method or cunstructor for these components to limit the number of characters. It would simplify things a lot. I need a JTextField to allow only 25 characters and allow backspaces. Thanks

    Here is the code that I am using. It seems to be working somewhat. The only problem now is that when you type the 26th key that new key overwrites what is in the 25th position. Is this the correct way of doing it and if so how do I get it to quit adding in the key that was just pressed?
    user_box.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent e) {
         if((user_box.getText().length() > 24)&&(e.getKeyCode() != KeyEvent.VK_BACK_SPACE)) {
    //     System.out.println(e.getKeyCode());
         e.consume();
         try {
              user_box.setText(user_box.getText(0,24));
         }catch(Exception ex) {}
         Toolkit kit = Toolkit.getDefaultToolkit();
         kit.beep(); //system beep
    });

  • How to limit number of chars in a CFGRIDCOLUMN

    Hi,
    I have a 2 column grid populated from a query. The grid is
    editable and will be submitted to an action page for database
    Delete, Insert, or Update. The first grid column corresponds to a
    MS SQL database column that is defined as varchar(3).
    Currently, if the user inputs 4 characters and submits, I get
    a SQL trunc error.
    There has to be a way to limit the number of characters in
    this cfgridcolumn to 3? How is it done?

    Well, you could check the number of characters on your action
    page, and bounce them back if it exceeds the maximum number, and
    you can "protect" the database by including a limiting function on
    the data in the insert statement, like LEFT(col, 3) so that
    regardless what they specify, you will only insert the first 3 into
    the database. You really should let them know if they entered too
    many, however.
    Phil

  • To limit number of characters in a text field...

    I did a little research. My goal is to limit the number of characters in the textfield by 50.
    If the results of my research are correct, I have to create a JFormattedTextField, then use a MaskFormatter with a mask of 50 asteriks. Is that correct? Any other suggestions?
    Thanks in advance.

    I've got a problem using a JFormattedTextField.
    Each time the the text field gains focus, the caret does no move to the end of the text. It appears at the start of it. plus, any text i typed will overwrite the character already typed in, as if you've pressed the INSERT button during typing in a text editor.
    What caused that and how do I resolve it?
    Thanks a lot for the help ;)

  • How to restrict number of characters for an input field

    Hi All,
    I have an input field.
    The max number of characters for this input field is 10.
    when a user enter more then 10 characters. it should prompt for an error or the input field should not allow to accpet the 11 character.
    how we do this in VC.
    need your helpful answers
    Rgds
    Srinivas

    Hi Srinu
    You could achieve this by configuring error messages under the formula:-
    Select the control properties and in the Input field at the Display tab write the formula
    "IF((@<LEN(text)>10),'appropriate message','Records available')"
    Note :- there is a LEN(text) under text functions in formula tab.
    Regards
    Navneet
    Message was edited by:
            Navneet Giria

  • How to find number of characters in a character string

    Hi,
      Can anyone please tell me about how to find the number of characters in a character string type variable.
    Reagards,
    Siva

    hi,
    Use STRLEN for Calculating String Length..
    Assign it to integer variable for Further Use.Suppse u need to find string length for "hai".. this piece of code will help u
    data:  var type string value 'hai',
             len type i.
    len = strlen(var).
    write len.

  • Limit number of characters in a text cell

    Hi Numbers Community,
    Is there a way to put a cap on the number of characters that can be written into a cell with Data Format set as Text?
    Thanks for your help!

    There doesn't seem to be a way to keep you from going over a limit on the number of characters in a cell but you can use Conditional Highlighting to alert you when you do go over the limit. This, for example, sets the background color of cell B9 to red if there are more than four characters in cell A9:
    The formula in B9:  =LEN(A9)
    SG

  • Limit number of characters in a textbox

    I'm trying to limit the number of characters a user can enter into the text box on a form.  
    Any help is appreciated.

    Thanks.
    I found this code, but am having problems using it (specifically the keyascii as integer part):
    Sub LimitKeyPress(ctl As Control, iMaxLen As Integer, KeyAscii As Integer)
    On Error GoTo Err_LimitKeyPress
        ' Purpose:  Limit the text in an unbound text box/combo.
        ' Usage:    In the control's KeyPress event procedure:
        '             Call LimitKeyPress(Me.MyTextBox, 12, KeyAscii)
        ' Note:     Requires LimitChange() in control's Change event also.
        If Len(ctl.Text) - ctl.SelLength >= iMaxLen Then
            If KeyAscii <> vbKeyBack Then
                KeyAscii = 0
                Beep
            End If
        End If
    Exit_LimitKeyPress:
        Exit Sub
    Err_LimitKeyPress:
        Call LogError(Err.Number, Err.Description, "LimitKeyPress()")
        Resume Exit_LimitKeyPress
    End Sub
    Sub LimitChange(ctl As Control, iMaxLen As Integer)
    On Error GoTo Err_LimitChange
        ' Purpose:  Limit the text in an unbound text box/combo.
        ' Usage:    In the control's Change event procedure:
        '               Call LimitChange(Me.MyTextBox, 12)
        ' Note:     Requires LimitKeyPress() in control's KeyPress event also.
        If Len(ctl.Text) > iMaxLen Then
            MsgBox "Truncated to " & iMaxLen & " characters.", vbExclamation, "Too long"
            ctl.Text = Left(ctl.Text, iMaxLen)
            ctl.SelStart = iMaxLen
        End If
    Exit_LimitChange:
        Exit Sub
    Err_LimitChange:
        Call LogError(Err.Number, Err.Description, "LimitChange()")
        Resume Exit_LimitChange
    End Sub

  • 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;

  • How to set number of characters in input field ?

    I am creating an input field dynamically (via CL_WD_INPUT_FIELD).
    I am binding the value (via BIND_VALUE) to an attribute with type CHAR30.
    I want to give the possibility to enter a number with 4 digits (0 - 9999).
    Is it possible to restrict the number of characters that can be entered to 4 (although the BIND_VALUE attribute has a type CHAR30, that allows 30)?
    I have tried it via set_length, bind_length but it seems that the length of the BIND_VALUE attribute overrules the length information...

    Hi Moritz,
    AFAIk you have no other option as using a NUM4 here.
    Set Length just sets the lengths of the inputfield according to the current character set ... count of charcters but does not limit the value you may enter
    Cheers
    Sascha

  • APEX Supplied HTML Editor (fckeditor) - Limit number of characters

    Hi
    Has anyone found a way of limiting the number of characters allowed in the HTML Editor that is supplied with APEX (3.1/fckeditor)
    I have had a look at the fckeditor web page and found a couple of plugins but I fear that this approach will require me to manually implement fckeditor, and not use the inbuilt one.
    I would also prefer to not do this with an application process as the user can overflow the editor and get the HTTP-400 Value param too long error.
    Regards
    Matt

    Dribble!
    does this help? Is their anyway to limit the character count on a textarea with html editor

  • Limiting the number of characters in a JTextField

    Hi I have 6 textfields and I don't want the user to enter more than 160 characters in a tet box. As soon as he reaches that limit, it shouldn't accept any more characters, how do I do this?
    One more thing, incase I register 5 textboxes to listen to the same event, how do I make out which textbox generated the event?
    Thanks

    The event generated from the textboxes has a method e.getSource() check that.
    To limit the number of characters extend PlainDocument and override insertString(...) and check the text size if the old size plus text to be inserted < your limit call super.insertString(..) else return.

  • Max number of characters in a JTextField

    I don't want to alowe more than 4 characters in a JTextField.
    Is where any method in Java corresponding to maxlength for textbox in Visual Basic??
    Or do I have to use KeyListener to check the situation for every key pressed?
    I'll be thankful for any help.

    write your own document & override the insertString() like the one below:
    import javax.swing.text.*;
    public class MyDocument extends PlainDocument {
         public void insertString(int offs, String s, AttributeSet a)
                                                          throws BadLocationException {
              if(getLength() > 4)
              //if(offs > 3)
              //if(getText(0, getLength()).length() > 4)
                   return;
              else
                   super.insertString(offs, s, a);            
    }

  • HT201320 how to limit number of emails in mac mail on iphone5

    Since I upgraded to ios7 my main email account within mac mail has been loading up to 1000 emails.  I want it to be as before, a limit of 200.  How???

    appartently the only solution is to mark all the emails as read but it eats up the internal memory. pretty dissappointing.

Maybe you are looking for

  • Need help, i need the

    Okay i have a major issue i need to get mail from GW out to some kind of external archive( we are attempting to use PST's IMAP isnt working out for the fact we have more than 65 thousand messages for some people ) The grouopwise connector for outlook

  • How can i select view attribute in a method

    hi how can i select view attribute in method and pass that attribute to procedure     public void DeleteAgr(Integer agrid) {                  ViewObject svo = this.findViewObject("AGR");                  //select current view id from agr and link id

  • Continous mDNSPlatformTCPConnect ("Permission denied") errors. What does this mean? What should I do to resolve this?

    MB Air (1.8GHz); MacOS 10.9.2 In the System Log I see frequent and, at times, continuous (up to several per second) entries like the following: 4/16/14 9:00:13.936 AM mDNSResponder[73]: ERROR: mDNSPlatformTCPConnect - connect failed: socket 63: Error

  • Outer join with nested tables

    I am dealing with a nested table (I simplified the case for purpose of posting): CREATE TABLE boris_main_tab ( IND_SSN          VARCHAR2(9) PRIMARY KEY, children          B_CHILDREN_TBL, ) nested table children stored as.... where B_CHILDREN_TBL is d

  • JTree listener question

    Hi, What are the TreeListener/TreeModel methods that would be called if I 1. double click on a row 2. expand/collaps a node Thanks in advance. Olek