I'm working with Java swing program. I want to insert in my JPanel, a JTextFieldFormat with a limit number of character and that convert all text in UPPER text. So I have build this code:
textCodiceFiscale = new JTextField();
textCodiceFiscale.setDocument(new PersonalizzaJtextField(numberCharacter));
DocumentFilter filter = new UppercaseDocumentFilter();
((AbstractDocument) textCodiceFiscale.getDocument()).setDocumentFilter(filter);
this is the UppercaseDocumentFilter class:
class UppercaseDocumentFilter extends DocumentFilter {
public void insertString(DocumentFilter.FilterBypass fb, int offset,
String text, AttributeSet attr) throws BadLocationException {
fb.insertString(offset, text.toUpperCase(), attr);
}
public void replace(DocumentFilter.FilterBypass fb, int offset, int length,
String text, AttributeSet attrs) throws BadLocationException {
fb.replace(offset, length, text.toUpperCase(), attrs);
}
}
This is PersonalizzaJTextField class:
public class PersonalizzaJtextField extends PlainDocument {
//private StringBuffer cache = new StringBuffer();
private int lunghezzaMax;
public PersonalizzaJtextField(int lunghezzaMax){
super();
this.lunghezzaMax = lunghezzaMax;
}
public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException{
if (str == null)
return;
if ((getLength() + str.length()) <= lunghezzaMax) {
super.insertString(offset, str, attr);
}
}
}
Now the problems are two:
1) with this code, I can insert only UPPER character in my JTextField but I the second line to limit number of Character, not works.
2) I want create a template for this JTextField, I must insert number or text in this mode:
6 characters 2 numbers 1 character 2 numbers 1 character 3 numbers 1 character.
Is possible to do this?
I want create a template for this JTextField, I must insert number or text in this mode:
Use a JFormattedTextField. You can use a MaskFormatter to have the JFormattedTextField do the editing for you. With a proper mask you can specify numbers or upper case characters.
Read the section from the Swing tutorial on How to Use Formatted Text Fields for more information and examples.
By the way the formatted text field creates the DocumentFilter for you automatically using the MaskFormatter, so you need a custom filter.
Bookmark the tutorial. You were also given a link to the tutorial in your last question on this topic. Use the tutorial for Swing basics.