0

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?

GVillani82
  • 17,196
  • 30
  • 105
  • 172
bircastri
  • 2,169
  • 13
  • 50
  • 119
  • 4
    You say `this now works`, and I can confirm that your code works - the input is limited to 10 characters. What exactly do you want to have fixed? – Andreas Fester Mar 09 '16 at 08:39
  • 1
    `DocumentFilter`, `DocumentFilter`, `DocumentFilter` anything else is wrong – MadProgrammer Mar 09 '16 at 10:18
  • And a working example of a DocumentFilter that does what you want is found in the Swing tutorial on [Implementing a DocumentFilter](http://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#filter). – camickr Mar 09 '16 at 20:46

0 Answers0