To limit and display the number of characters in a Jtextarea

Asked

Viewed 2,234 times

5

I have a supplier registration window, and I’d like to insert a jTextArea so that the user has the option to enter some observation about the supplier.

inserir a descrição da imagem aqui

The idea is that, limit the amount of characters to be typed and show above the jTextArea the amount left and how many characters were typed.

How can I do this? I am using Netbeans and in the database the field that will store this information is like TEXT, MySQL.

  • This here is exactly what you need.

1 answer

7


As demonstrated in this answer in Soen, you can do this using the class DocumentFilter.

I changed the example of the answer using a JTextArea, but the effect is the same, after all, JTextField and JTextArea are both text fields. I added comments on some points that I found relevant from the code as well:

import java.awt.BorderLayout;
import java.awt.Toolkit;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;

public class LimitarTextAreaTest extends JFrame {

    private JTextArea textArea;
    private DefaultStyledDocument doc;
    private JLabel remaningLabel = new JLabel();

    public LimitarTextAreaTest() {
        setLayout(new BorderLayout());

        textArea = new JTextArea(5, 15);
        doc = new DefaultStyledDocument();

       //aqui é atribuido um filtro ao DefaultStyledDocument, é esta classe que vai
       //limitar o número máximo de caracteres, basta alterar o 500
       //para o valor maximo desejado
        doc.setDocumentFilter(new DocumentSizeFilter(500));
        //neste trecho, foi sobrescrito um DocumentListener,
        //que monitora alterações dentro do campo de texto
        //sempre que uma alteração for realizada, será invocado
        //o método updateCount(), que vai atualizar o numero
        //de caracteres restantes
        doc.addDocumentListener(new DocumentListener() {
            @Override
            public void changedUpdate(DocumentEvent e) {
                updateCount();
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                updateCount();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                updateCount();
            }
        });
        //finalmente o DefaultStyledDocument foi
        //atribuido ao seu campo de texto
        textArea.setDocument(doc);
        //insere o valor inicial restante
        updateCount();

        add(textArea, BorderLayout.NORTH);
        add(remaningLabel, BorderLayout.SOUTH);

        setLocationRelativeTo(null);
        pack();
    }

    private void updateCount() {
        remaningLabel.setText((500 - doc.getLength()) + " caracteres restantes");
    }

    public static void main(String[] args) {
        new LimitarTextAreaTest().setVisible(true);
    }

    //esta classe que faz a limitação de caracteres
    class DocumentSizeFilter extends DocumentFilter {

        int maxCharacters;
        boolean DEBUG = false;

        public DocumentSizeFilter(int maxChars) {
            maxCharacters = maxChars;
        }

        public void insertString(DocumentFilter.FilterBypass fb, int offs,
                String str, AttributeSet a)
                throws BadLocationException {
            if (DEBUG) {
                System.out.println("in DocumentSizeFilter's insertString method");
            }

            //Isto rejeita novas inserções de caracteres se
            //a string for muito grande. Outra opção seria
            //truncar a string inserida, de forma que seja
            //adicionado somente o necessário para atingir
            //o limite máximo permitido
            if((fb.getDocument().getLength() + str.length()) <= maxCharacters) {
                super.insertString(fb, offs, str, a);
            } else {
                Toolkit.getDefaultToolkit().beep();
            }
        }

        public void replace(DocumentFilter.FilterBypass fb, int offs,
                int length,
                String str, AttributeSet a)
                throws BadLocationException {
            if (DEBUG) {
                System.out.println("in DocumentSizeFilter's replace method");
            }
            //Isto rejeita novas inserções de caracteres se
            //a string for muito grande. Outra opção seria
            //truncar a string inserida, de forma que seja
            //adicionado somente o necessário para atingir
            //o limite máximo permitido
            if((fb.getDocument().getLength() + str.length() - length) <= maxCharacters) {
                super.replace(fb, offs, length, str, a);
            } else {
                Toolkit.getDefaultToolkit().beep();
            }
        }

    }
}

Code above working:

inserir a descrição da imagem aqui

Just pointing out that the class DocumentSizeFilter has been taken from one of the examples of the official documentation link to here.

  • Thank you so much for the strength... Fit like a glove.

  • Just one more question, would you have to create an event with jTextArea? Like when you click to type something start counting?

  • @Valdecir good, you just need to set one DocumentListener and the class DocumentSizeFilter in your jtextarea(copy the answer and save in a separate file so your code is more organized) as it was done in the code. And also you need to add in your class the method updateCount(), it is he who updates the information. In the image, just below jtextArea has a name Jlabel remaningLabel, replace with its component that wants the remaining character count message to appear.

  • Very nice guy!! Thanks again!

  • Excellent example, still added a counter and a GIF, congratulations!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.