Question

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?

Was it helpful?

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);
     }
  }
});

OTHER TIPS

you need to define a key listener and inside that surely we need to define implemented methods , the next code is my solution I hope it helps.

////
textfield.addKeyListener(new KeyListener() {
                public void keyPressed(KeyEvent e) {
                    // TODO Auto-generated method stub
                    if(textfield.getLineCount() == maximum_number_of_your_default) {
                        c = ta.getCaret(); 
    // c is an object of Caret class as : Caret c; initialization only.
                        a = c.getDot();
    // a is an integer value initialized by zero as : int a = 0;
                    }
                    if(ta.getLineCount() > maximum_number_of_your_default){
                        c.moveDot(a);// To retrieve the caret to the last row.
                    }
    // to show line segment on the output with each enter-press key :
                    if(e.getExtendedKeyCode() == KeyEvent.VK_ENTER)
                        System.out.println("!!!!!" + ta.getLineCount() + "  " 
                        + ta.getText());    
                }
    // default methods of KeyListener class
                public void keyReleased(KeyEvent arg0) {
                    // TODO Auto-generated method stub

                }

                public void keyTyped(KeyEvent arg0) {
                    // TODO Auto-generated method stub

                }
            });
////

It my idea I hope it is correct , good luck, one world , one god , one solution for each .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top