Reputation: 1286
Suggestions for a better title are welcome!
There are two fields (net- and gross price), both of which are editable. They have their own ModifyListeners attached, updating the other Text's value upon the percentage of applicable VAT.
So that's the theory.
The reality is that when any of the listeners set the other Text's text property, the other listener triggers, which triggers the caller Text's listener and so on till it reaches StackOverflow. :-)
Question: Is there a well-known way/pattern to avoid this behaviour?
I can only think of a field in the Dialog's class let's say:
boolean stopOverflow; // Stops Listeners from triggering each other
And make the listeners checking for it; setting it true/false whether we're already in a Modification event. Hoping SWT is single threaded.
A similar question can be found here:
How to limit ModifyListener for user interaction only
Upvotes: 1
Views: 173
Reputation: 42
There's a more simple solution. It needs no additional field in the Dialog's class and is only one additional if.
private Text netPrice; // Let's say this holds your net-price text
netPrice.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
if (netPrice == Display.getCurrent().getFocusControl()) {
//
// Do your logic here, it's overflow safe
//
}
}
});
Implement your gross-price Text the same way.
Upvotes: 1
Reputation: 111217
Calling removeModifyListener
before doing the setText
and then calling addModifyListener
afterwards is one of the usual ways to approach this.
Keep the modify listener as a field in the dialog class so you can keep track of it:
private ModifyListener modifyListener = new MyModifyListener();
...
text.removeModifyListener(modifyListener);
text.setText(....);
text.addModifyListener(modifyListener).
Upvotes: 2