• 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
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

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.
 
You can't have everything. Where would you put it?
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic