Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Fixed size JTextField

 
Indika Hewage
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
How can I create a fixed size TextField? For example, JTextField(4) should only allow to enter 4 characters but we can enter more than 4 characters.

Thanks.
 
Sunil Kumar Gupta
Ranch Hand
Posts: 824
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use This

import javax.swing.JTextField;
import javax.swing.text.PlainDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.AttributeSet;


public class CharLimiter extends PlainDocument
{
int x=0;
CharLimiter(int x)
{
this.x=x;
}
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if(str.length() > x-1 || this.getLength()> x-1) {
java.awt.Toolkit.getDefaultToolkit().beep();
return;
}
super.insertString(offs, str, a);
}
}



Now ur text field will be initialized as


JTextField txtName=new JTextField(new CharLimiter(4),"",5);


Enjoy

 
Indika Hewage
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Sunil.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!