wood burning stoves*
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JTextField - Restrict length " Watch "JTextField - Restrict length " New topic
Author

JTextField - Restrict length

Sajee Joseph
Ranch Hand

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

Joined: Sep 09, 2001
Posts: 12
Hi,
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();
System.out.println("hello1::"+len);
if(len>2)
{
jTextField1.setEditable(false);
}
else
{
jTextField1.setEditable(true);
}
}
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.
Regards
PremilaViswanathan

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

Paul Stevens
Ranch Hand

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

Joined: Aug 23, 2001
Posts: 23
hi,
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.
Jeff
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();
myTextField.setDocument(myDocument);
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: JTextField - Restrict length
 
Similar Threads
Retaining Focus in Swing
JTextField
System Date
For Each loop problem.
Tab Order