开发者

delay in text input

User is typing something in Text component. When he is stopped typing for 1 second I want get text and handle it. I try to do like that

final Timer timer = new Timer();
    Text text = new Text(shell, SWT.BORDER);
    text.addModifyListener(new ModifyListener() {
        @Override
        public void modifyText(ModifyEvent e) {
            timer.purge();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
开发者_StackOverflow                    //handler
                    System.out
                            .println("MainClass.main(...).new SelectionAdapter() {...}.widgetSelected(...).new TimerTask() {...}.run()");
                }
            }, 500);
        }
    });

But this code works incorrectly


I asked by myself and I'll answer by myself :) timer is private member

Text text = new Text(shell, SWT.BORDER);
    text.addModifyListener(new ModifyListener() {
        @Override
        public void modifyText(ModifyEvent e) {
            if(timer != null){
                timer.cancel();
            }
            timer = new Timer();                
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //handler
                    System.out
                        .println("MainClass.main(...).new SelectionAdapter() {...}.widgetSelected(...).new TimerTask() {...}.run()");
                    timer.cancel();
                }
            }, 1000);
        }
    });

works!


You can do it like this:

double last_edit = 0;
// this method shall be called on initialization of your Text component
void run() {
    new Thread(new Runnable() {
        public void run() {
            if (last_edit < 0) {
                // hande your text here
                last_edit = 1;
            } else {
                last_edit -= 0.1d;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
            }
        }
    }).start();
}
 Text text = new Text(shell, SWT.BORDER);
 text.addModifyListener(new ModifyListener() {
    @Override
    public void modifyText(ModifyEvent e) {
        last_edit = 1;
    }
 });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜