I'm working on a Java swing program and I want to create a JTextField
, with limitated number of characters. So, I have created this class:
public class PersonalizzaJtextField extends PlainDocument {
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, when I try to create a JTextField, limiting the numbers of characthers, it does'n work. I have used this code:
public class Main extends JFrame {
JTextField textfield1;
JLabel label1;
public void init() {
setLayout(new FlowLayout());
label1 = new JLabel("max 10 chars");
textfield1 = new JTextField(15);
add(label1);
add(textfield1);
textfield1.setDocument(new PersonalizzaJtextField(10));
setSize(300,300);
setVisible(true);
}
}
How can I fix it?