views:

291

answers:

3

I notice that the ModifyListener will be triggered regardless the action is caused by user or system itself, for instance,

Text t = new Text(shell, SWT.BORDER);
t.addModifyListener(new TModifyListener());

...............................................

private class TModifyListener implements ModifyListener
{

 @Override
 public void modifyText(ModifyEvent event)
 {

  Text text = (Text) event.widget;
  t.setText(process(text.getText()));
 }
}

This will cause infinite loop and crash the program. Do you guys have any idea how to disable the event listening if the event is generated by system, and enable it if the event is caused by user?

+1  A: 

I don't know swt but...

If process is idempotent then perhaps you could setText only if it is different from getText

Another option is to set some property on the widget in the first callback which you can query, unset and not call setText in the second callback.

Hemal Pandya
+2  A: 

Couldn't you just set a ThreadLocal in your listener and check it when it's re-entered?

edit: In fact it wouldn't even need to be a ThreadLocal, since SWT is single-threaded. Just set a boolean field on the listener.

private class TModifyListener implements ModifyListener {

    private boolean _setting;

    @Override
    public void modifyText(ModifyEvent event)
    {
            if(!_setting) {
                _setting = true;
                try {
                    Text text = (Text) event.widget;
                    t.setText(process(text.getText()));
                } finally {
                    _setting = false;
                }
            }
    }
}
kprevas
This method works provided the event broadcasting is run in sequential fashion. What I afraid is the event broadcasting may run in async / concurrent fashion. That might cause problem.
janetsmith
You can make the body of `_setting` contained in a `synchronized` to avert this problem.
Paul Lammertsma
A: 

Have you investigated if there is any difference in the event's source()?

Paul Lammertsma