Solved

Set Maxlength for JTextField??

Posted on 2004-03-22
27
1,810 Views
Last Modified: 2012-06-27
is there any way to set the maxlenth of the Jtextfield ?? restricted to 10 char
0
Comment
Question by:M_I2
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 10
  • 8
  • 5
  • +3
27 Comments
 
LVL 14

Expert Comment

by:StillUnAware
ID: 10655740
//something like that :)

import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;

public class DocumentUse extends JFrame {
  DocumentUse() {
    Container cp = getContentPane();
    final JTextField tf = new JTextField();
    tf.getDocument().addDocumentListener(new DocumentListener() {
      public void changedUpdate(DocumentEvent e) {
        if(tf.getText().length() > 10)
          tf.setText(tf.getText().substring(10));
      }
      public void insertUpdate(DocumentEvent e) {
        if(tf.getText().length() > 10)
          tf.setText(tf.getText().substring(10));
      }
      public void removeUpdate(DocumentEvent e) {
        if(tf.getText().length() > 10)
          tf.setText(tf.getText().substring(10));
      }
    });
    cp.add(tf);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();
    setVisible(true);
  }
  public static void main(String[] args) {
    DocumentUse du = new DocumentUse();
  }
}
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 10656104
Can't get the above code to work.

Another way would be:

int MaxLen;
String mTF;
mTF = myTextField.getText().length()>MaxLen?myTextField.getText().substring(0,MaxLen):myTextField.getText();

myTextField.setText(mTF);
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 50 total points
ID: 10656357
This is a case that would be better using a custom document than a document listener. see http://oldlook.experts-exchange.com:8080/Programming/Programming_Languages/Java/Q_20747816.html
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 37

Accepted Solution

by:
zzynx earned 75 total points
ID: 10656419
I made a working one. Just test it.

import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;

public class DocumentUse extends JFrame {
   
    public class MyDocument extends PlainDocument {
   
        private int maxAllowedChars = 0;

        public MyDocument(int maxAllowed) {
            super();
            maxAllowedChars = maxAllowed;
        }

        public void insertString(int index, String s, AttributeSet a)
                                            throws BadLocationException {
             if (s == null || s.length() == 0)
                 return;
             StringBuffer t = new StringBuffer(getLength() + s.length());
             t.append(getText(0, index));
             t.append(s);
             t.append(getText(index, getLength() - index));
             if (t.length()>maxAllowedChars) return; // don't allow more than x chars
             super.insertString(index, s, a);
        }
    }    
   
    public class MyField extends JTextField {
        public MyField(int width) { super(width); }
        public MyField() { super(); }
        protected Document createDefaultModel() {
            return new MyDocument(10);
        }
    }
   
    public DocumentUse() {
        Container cp = getContentPane();
        final MyField tf = new MyField();

        cp.add(tf);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }
 
  public static void main(String[] args) {
    DocumentUse du = new DocumentUse();
  }
}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10656432
...but i just posted a (link to a) working one...?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10656446
Sorry CEHJ, I didn't refresh before I posted.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10656458
No problem
0
 
LVL 5

Expert Comment

by:twobitadder
ID: 10660895
doesn't
 textField.setColumns(10);
do this?
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 10661270
>> do this?

Lol, that's what I was thinking and have never tried it!! But, yeh, it should - shouldn't it?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10665181
>> it should - shouldn't it?
LOL also

Why don't you try it?
In my example replace

        final MyField tf = new MyField();

by

        final JTextField tf = new JTextField();
        tf.setColumns(10);

P.S. If you don't want to try it yourself, here's the result: it doesn't work that way.
;-)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10666743
>>here's the result: it doesn't work that way.

Too late - i could have saved you both the bother ;-) Must be worth a few points in a split for the person who explains this conundrum...
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10667155
I don't understand what you mean to say CEHJ.

Hey M_I2, still alive?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10667344
>>I don't understand what you mean to say CEHJ.

By my first, or my second sentence?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10668002
Both
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10668111
>>Too late - i could have saved you both the bother

Meant that everyone was asking if tf.setColumns(10); or similar would work - it doesn't - and had i got there in time i could have told everyone

>>Must be worth a few points in a split for the person who explains this conundrum...

Means that i have never taken the time and trouble to discover *why* this doesn't work and i'm encouraging someone to find out and also encouraging M_I2 to give the discoverer some points in a split.

All clear?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10668216
>> All clear?
Yeah. Thanks for explaining.

>> Means that i have never taken the time and trouble to discover *why* this doesn't work
Why should it. It has nothing to do with the number of characters you can input.

The comment in the constructor
            public JTextField(int columns)
says

     * @param columns  the number of columns to use to calculate
     *   the preferred width; if columns is set to zero, the
     *   preferred width will be whatever naturally results from
     *   the component implementation

the java help for
           SetColumn()
says:
Sets the number of columns in this text field. A column is an approximate average character width that is platform-dependent.

So, its all about width, not about # of characters allowed to input.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10668244
>> and also encouraging M_I2 to give the discoverer some points in a split.
If M_I2 is still alive ;)
I'm willing to accept them ;)
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 10668261
setColumns() just sets the display width, but you can type as much in as you like. How about that?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10668268
Thanks for saving me the trouble ;-)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10668392
>> setColumns() just sets the display width, but you can type as much in as you like.
>> How about that?
Too late ;)

>> Thanks for saving me the trouble ;-)
You're welcome
;)
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 10668443
>> Too late ;)
 ?

Where's that been said explicitly before? Remember, the question is for the benefit of the questioner, not the experts' fraternity.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10668581
>>Where's that been said explicitly before?
In one of my previous comments:
      >> So, its all about width, not about # of characters allowed to input.
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 10668610
ok, point taken. I'll blame it on EE's oldlook posting bug earlier.
0
 

Author Comment

by:M_I2
ID: 10697811
Sorry for late reply ;) but i was away past few days......

i would try out these code now.
0
 

Author Comment

by:M_I2
ID: 10697838
i think that really works....but need some time to digest these codes

>> Hey M_I2, still alive?
and also actually i am alive!! but not available at all times

Well that's about it thanks for all your all for helping ;)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10697946
8-)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10701958
Thanks for accepting.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
couple of eclipse 5 52
use lov values 2 72
servlet web applications   metadata-complete="true" or false 3 200
How to configure empty element in XML Document parser? 15 44
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question