[Webinar] Streamline your web hosting managementRegister Today

x
?
Solved

Set Maxlength for JTextField??

Posted on 2004-03-22
27
Medium Priority
?
1,872 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
  • 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 17

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 150 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
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
LVL 37

Accepted Solution

by:
zzynx earned 225 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 17

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 17

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 17

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 17

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: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying 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

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month10 days, 1 hour left to enroll

591 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