Hen Shabat Hen Shabat - 1 year ago 70
Java Question

How to stop key repeat on continuous keypress?

For example if I pressed the key "1" for few seconds the result in my

will be "1111111111111".

Is there any way to stop it after one char?

Answer Source

If I understand the problem correctly, you could use a DocumentFilter for this, and only allow the text to be inserted if let's say the delay of the keypress is above 0.5 seconds.


import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class Example {

    public Example() {
        JTextArea textArea = new JTextArea();
        ((AbstractDocument) textArea.getDocument()).setDocumentFilter(new DocumentFilter() {
            String lastStr = "";
            long time = System.currentTimeMillis();

            public void replace(FilterBypass fb, int offset, int length, String str, AttributeSet attr)
                    throws BadLocationException {
                long delay = System.currentTimeMillis() - time;
                time = System.currentTimeMillis();
                if (str.equals(lastStr) && delay <= 500) {
                lastStr = str;
                super.replace(fb, offset, length, str, attr);

        JFrame frame = new JFrame();
        frame.setSize(800, 600);

    public static void main(String[] args) {
        new Example();