File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes JTextField - Restrict length Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JTextField - Restrict length " Watch "JTextField - Restrict length " New topic

JTextField - Restrict length

Sajee Joseph
Ranch Hand

Joined: Jan 17, 2001
Posts: 200
I have a JTextField. I would like it to be 4 cloumn wide, but accept only 3 characters?
How do i do that?

Joined: Sep 09, 2001
Posts: 12
Add keylistener to the concerned textfield and in the keypressed event write the following code
JTextField jTextField1=new JTextField();
jTextField1.setText(""); //intially the textfield is empty

void jTextField1_keyPressed(KeyEvent e) {
int len=jTextField1.getText().length();
This allows only three characters to be typed in the textfield.
U can clear the textfield by means a clear button and retype. Everytime u type fresh , u cannot enter more than 3 characters.
Hope this would be quite useful to u.

Originally posted by Sajee Joseph:
I have a JTextField. I would like it to be 4 cloumn wide, but accept only 3 characters?
How do i do that?

Paul Stevens
Ranch Hand

Joined: May 17, 2001
Posts: 2823
Does that prevent paste operations greater than 3?
Jeff Chang

Joined: Aug 23, 2001
Posts: 23
To disable cut/copy/paste in a JtextField, you can create a JTextField and override the copy() and paste()
methods as below:
JTextField myTextField = new JTextField()
public void cut() {};
public void copy() {};
public void paste(){};
This is also disable cut().
Good luck.
Renee Zhang
Ranch Hand

Joined: Sep 10, 2001
Posts: 72
Another way to accept only 3 characters in your textField is to create your Document
class myDocument extends PlainDocument {
public void insertString (int offset, String s, AttributeSet attributeSet) throws BadLocationException {
try {
if (offset <3)
super.insertString(offset, s, attributeSet);
} catch (Exception e) {
// Do nothing about it

Then in your file
MyDocument myDocument = new MyDocument();
I agree. Here's the link:
subject: JTextField - Restrict length
It's not a secret anymore!