【问题标题】:JTextField sends data after no change event fired for the last 2 secondsJTextField 在最后 2 秒内未触发任何更改事件后发送数据
【发布时间】:2013-11-01 21:44:52
【问题描述】:

要求很简单: 文本字段用于从用户那里获取一些信息。如果用户在最后 2 秒内没有输入新字符,则使用文本字段中的文本并提交到某个界面。接口还不重要。

我必须将 propertyChange 或键侦听器附加到文本字段。每次用户添加新字符时,我的内部字符串缓冲区都会更新。

问题: 我需要一些模板或设计模式来实现异步线程,该线程在触发动作之前等待 2 秒。在 2 秒的延迟内线程可以被重置,所以线程再次等待 2 秒。

因此,如果文本字段发生更改,线程将被重置。如果线程等待 2 秒,则可以使用文本字段数据填充界面。

我考虑过创建一个延迟 2 秒的线程并在检测到文本字段更改时中断该线程。线程被中断后,会触发一个新的延迟线程,但我想知道是否有人知道我可以直接使用的 java 类。

【问题讨论】:

    标签: java multithreading delay textfield


    【解决方案1】:

    我已经实现了一次,你可以使用java.swing.Timer,例如,只需将重复设置为false(只触发一次)并在每次用户输入字符时重置它(测试代码here

    例如:

    import javax.swing.Timer;
    
    ...
    
    private Timer t; //declare "global" timer (needs to bee seen from multiple methods)
    
    private void init() {
    
        t = new Timer(2000, putYourUsefullActionListenerHere);
        //the one that will acctually do something after two seconds of no change in your field
    
        t.setRepeats(false); // timer fires only one event and then stops
    }
    
    private void onTextFieldChange() { //call this whenever the text field is changed
        t.restart();
        //dont worry about "restart" and no start, it will just stop and then start
        //so if the timer wasnt running, restart is same as start
    }
    
    private void terminate() {
        //if you want for any reson to interrupt/end the 2 seconds colldown prematurelly
        //this will not fire the event
        t.stop();
    }
    

    【讨论】:

    • +1 建议使用 Swing Timer。 -1 未在论坛中发布代码。
    • @camickr :更好吗? :)
    【解决方案2】:

    我必须将 propertyChange 或键侦听器附加到文本字段

    您应该使用 DocumentListener。每当在文本字段中添加/删除文本时,您都会收到通知。

    阅读 How to Write a Document Listener 上的 Swing 教程部分以获取更多信息和示例。该教程还有一个关于How to Use a Swing Timer的部分。

    【讨论】:

    • +1 我想接受 2 个答案,但只能是一个。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-22
    • 2014-08-28
    • 1970-01-01
    • 2020-09-25
    • 2017-10-08
    • 1970-01-01
    相关资源
    最近更新 更多