Mahbubur Rahman Khan
Mahbubur Rahman Khan

Reputation: 415

how to start a function after stop typing in a JTextField in java

how to start a function after stop typing in a JTextField. Not for every key release. If two key release time difference is greater than 1 second then it will run this function. Otherwise wait for 1 second.

Upvotes: 3

Views: 3501

Answers (2)

Peti
Peti

Reputation: 1700

If you don't mind using two libraries, this is very easy to solve with RxSwing and RxJava:

    EventQueue.invokeLater(() -> {
        try {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.getContentPane().setLayout(new BorderLayout());

            JTextField textField = new JTextField(30);
            frame.getContentPane().add(textField, BorderLayout.NORTH);

            // HERE
            SwingObservable.fromDocumentEvents(textField.getDocument())
                    .debounce(1, TimeUnit.SECONDS)
                    .map(documentEvent -> textField.getText())
                    .subscribe(System.out::println);

            frame.setVisible(true);
            frame.pack();
        } catch (final Exception e) {
            e.printStackTrace();
        }
    });

Upvotes: 2

MadProgrammer
MadProgrammer

Reputation: 347194

Use a Swing Timer and a DocumentListener, each time the Document is updated, reset the Timer

Have a look at How to use Swing Timers and Listening for Changes on a Document for more details

As a, simple, example...

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class Test {

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

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {

            JTextField field = new JTextField(20);
            JLabel label = new JLabel("Waiting");

            DeferredDocumentListener listener = new DeferredDocumentListener(1000, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // Execute your required functionality here...
                    label.setText(label.getText() + ".");
                }
            }, true);
            field.getDocument().addDocumentListener(listener);
            field.addFocusListener(new FocusListener() {
                @Override
                public void focusGained(FocusEvent e) {
                    listener.start();
                }

                @Override
                public void focusLost(FocusEvent e) {
                    listener.stop();
                }
            });

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            add(field, gbc);
            add(label, gbc);
        }

    }

    public class DeferredDocumentListener implements DocumentListener {

        private final Timer timer;

        public DeferredDocumentListener(int timeOut, ActionListener listener, boolean repeats) {
            timer = new Timer(timeOut, listener);
            timer.setRepeats(repeats);
        }

        public void start() {
            timer.start();
        }

        public void stop() {
            timer.stop();
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            timer.restart();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            timer.restart();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            timer.restart();
        }

    }

}

Upvotes: 9

Related Questions