Solved

Set Maxlength for JTextField??

Posted on 2004-03-22
27
1,817 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
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 
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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

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

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

705 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