JTextField

if I used a JTextField, is there any way that I can limit how many characters can be inputed to the text field?  I want a max of 5 chars to be entered into the text field, and I dont want to have to check the length and pop up a dialog telling the user they've exceeded 5 chars, I just want to flat out limit it.
LVL 1
mrquijaAsked:
Who is Participating?
 
moirafishConnect With a Mentor Commented:
As far as I can see, you have to extend the document model…
This one will even work if you paste in from the clipboard

define your text field:

MaxCharsField jTextField1 = new MaxCharsField(5);

where MaxCharsField & MaxCharsDocument are defined as follows:

import javax.swing.*;
import javax.swing.text.*;

public class MaxCharsField extends JTextField {
  public MaxCharsField(int maxchars) {
      MaxCharsDocument d = (MaxCharsDocument)this.getDocument();
      d.maxchars = maxchars;
  }

  protected Document createDefaultModel() {
    return new MaxCharsDocument();
}

static class MaxCharsDocument extends PlainDocument {

  int maxchars;

  public void insertString(int offs, String str, AttributeSet a)
    throws BadLocationException {
    int len = this.getLength();
    if (len >= maxchars || str == null) {
      return;
    }
    if (len + str.length() > maxchars) {
      str = str.substring(0, maxchars-len);
    }

    super.insertString(offs, str, a);
  }
}
}

0
 
mrquijaAuthor Commented:
Moirafish, thank you for your wonderful help.  Question, how does your class know how long to construct the textfield?  Is there anyway that I can change the width of the jtextfield to whatever I specify?

0
 
mrquijaAuthor Commented:
Nevamind, I used

super.setColumns(int width)

to do what I needed to do. Thanks again
0
 
moirafishCommented:
Thanks for the points :-)

The easiest thing to do for the width is just set the column number of the JTextField..

in the constructor
public MaxCharsField(int maxchars)
do
super(maxchars);

this means the preferred size of the JTextField will fit maxchars characters
but since the default font of JTextField is variable font, maxchars characters doesn’t always fit the field…
eg: @@@@@ would fill a maxchars 5 field but 11111 would half fill it.

you could set the font to a fixed font such as in MaxCharsField constructor do:

Font monoFont = new Font("Monospaced", Font.PLAIN, 12);
this.setFont(monoFont);

& then the sizing seems to work better if you make maxchars+1 columns, ie.
super(maxchars+1);

hope you find something that works!
Moira

0
All Courses

From novice to tech pro — start learning today.