我有一个 JTextComponent,我想在用户停止编辑该 JTextComponent 中的文本一段时间时调用一个方法。我想每次修改模型时都启动一个计时器,并在另一个文本编辑到达时取消它,但它给我一种感觉,这不是最好的选择。您能分享一下如何实施此类行为的经验吗?
是的,这可能是最好的决定。您甚至不会取消计时器,而只需从 DocumentListener 中调用计时器上的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();
});
}
}