• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Fixed size JTextField

 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 824
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Sunil.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic