在文本组件的内容未编辑一段时间时调用方法

时间:2016-03-20 05:55:33

标签: java swing jtextfield jtextarea jtextcomponent

我有一个JTextComponent,我想在用户停止编辑该JTextComponent中的文本一段时间时调用一个方法。我想在每次修改模型时启动一个计时器,如果另一个文本编辑到达则取消它,但它让我觉得它不是最好的设计。您能否分享一下如何实施此类行为?

1 个答案:

答案 0 :(得分:4)

是的,这可能是最好的决定。您甚至不取消Timer,而只是从DocumentListener中调用Timer上的restart()

例如,如果编辑处于非活动状态超过2秒,则会将JTextField背景变为红色的程序:

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

@SuppressWarnings("serial")
public class ResetCounter2 extends JPanel {
    private static final int TIMER_DELAY = 2000; // 2 seconds
    public static final Color LATE_BACKGROUND = Color.RED;
    private JTextField textField = new JTextField(10);
    private Timer timer = new Timer(TIMER_DELAY, new TimerListener());

    public ResetCounter2() {
        textField.getDocument().addDocumentListener(new MyDocListener());
        add(textField);

        // make sure timer does not repeat and then start it
        timer.setRepeats(false);
        timer.start();
    }

    private class MyDocListener implements DocumentListener {

        @Override
        public void changedUpdate(DocumentEvent e) {
            docChanged();
        }

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

        @Override
        public void removeUpdate(DocumentEvent e) {
            docChanged();
        }

        private void docChanged() {
            textField.setBackground(null);
            timer.restart();
        }

    }

    private class TimerListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            textField.setBackground(LATE_BACKGROUND);
        }
    }

    private static void createAndShowGui() {
        ResetCounter2 mainPanel = new ResetCounter2();

        JFrame frame = new JFrame("ResetCounter");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGui();
        });
    }
}