mrquija
asked on
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.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Nevamind, I used
super.setColumns(int width)
to do what I needed to do. Thanks again
super.setColumns(int width)
to do what I needed to do. Thanks again
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
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
ASKER