javaswingjtextareadocumentlistener

JTextArea row limit


So, I have a JTextArea.

I need it to be setup in a way that it prevents user from entering more than 4 rows of text. I found a way to count lines. But copy/paste has to be taken into account too. And I am not using monospaced font.

Is there a way of doing that taken all this into account?


Solution

  • why not add a DocumentListener and check the amount of lines each time text is removed, inserted or changed in the JTextArea:

    JTextArea.getDocument().addDocumentListener(new DocumentListener() {
      public void changedUpdate(DocumentEvent e) {
        check();
      }
      public void removeUpdate(DocumentEvent e) {
        check();
      }
      public void insertUpdate(DocumentEvent e) {
        check();
      }
    
      public void check() {
         if (JTextArea.getLineCount()>4){//make sure no more than 4 lines
           JOptionPane.showMessageDialog(null, "Error: Cant have more than 4 lines", JOptionPane.ERROR_MESSAGE);
         }
      }
    });