Set Maxlength for JTextField??

is there any way to set the maxlenth of the Jtextfield ?? restricted to 10 char
M_I2Asked:
Who is Participating?
 
zzynxSoftware engineerCommented:
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
 
StillUnAwareCommented:
//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
 
krakatoaCommented:
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
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

 
CEHJCommented:
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
 
CEHJCommented:
...but i just posted a (link to a) working one...?
0
 
zzynxSoftware engineerCommented:
Sorry CEHJ, I didn't refresh before I posted.
0
 
CEHJCommented:
No problem
0
 
twobitadderCommented:
doesn't
 textField.setColumns(10);
do this?
0
 
krakatoaCommented:
>> do this?

Lol, that's what I was thinking and have never tried it!! But, yeh, it should - shouldn't it?
0
 
zzynxSoftware engineerCommented:
>> 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
 
CEHJCommented:
>>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
 
zzynxSoftware engineerCommented:
I don't understand what you mean to say CEHJ.

Hey M_I2, still alive?
0
 
CEHJCommented:
>>I don't understand what you mean to say CEHJ.

By my first, or my second sentence?
0
 
zzynxSoftware engineerCommented:
Both
0
 
CEHJCommented:
>>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
 
zzynxSoftware engineerCommented:
>> 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
 
zzynxSoftware engineerCommented:
>> 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
 
krakatoaCommented:
setColumns() just sets the display width, but you can type as much in as you like. How about that?
0
 
CEHJCommented:
Thanks for saving me the trouble ;-)
0
 
zzynxSoftware engineerCommented:
>> 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
 
krakatoaCommented:
>> Too late ;)
 ?

Where's that been said explicitly before? Remember, the question is for the benefit of the questioner, not the experts' fraternity.
0
 
zzynxSoftware engineerCommented:
>>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
 
krakatoaCommented:
ok, point taken. I'll blame it on EE's oldlook posting bug earlier.
0
 
M_I2Author Commented:
Sorry for late reply ;) but i was away past few days......

i would try out these code now.
0
 
M_I2Author Commented:
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
 
CEHJCommented:
8-)
0
 
zzynxSoftware engineerCommented:
Thanks for accepting.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.