File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JTextField - Restrict length

 
Sajee Joseph
Ranch Hand
Posts: 200
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2823
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does that prevent paste operations greater than 3?
 
Jeff Chang
Greenhorn
Posts: 23
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 72
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic