开发者

Swing: programatically modifying the UI without triggering callbacks

开发者 https://www.devze.com 2023-01-27 21:36 出处:网络
If it is taken for granted that you need to modify programatically an element of the UI, like, say, a JComboBox\'s selected item without triggering any modification/notification event, then how to do

If it is taken for granted that you need to modify programatically an element of the UI, like, say, a JComboBox's selected item without triggering any modification/notification event, then how to do it relatively cleanly?

Surely I can detach all the listeners then reattach them once I've modified what I want to modify but, typically, how is one supposed to do that? (once again, by considering that it is granted that that some element shall be modified and that it is considered granted that those modification should not trigger any callbacks).

P.S: I did do it by writing methods that do actually detach all the listeners,开发者_StackOverflow社区 perform the modification, then re-attach all the listeners and it does work, but it seems a bit crappy to me.


Usually, the problem are not all listeners, but one - our own one. A typical pattern for ignoring such events is following:

private boolean ignoreEvents;

public void initialize(...) {
   ignoreEvents = true;
   try {
      // set the combobox value
   }
   finally {
      ignoreEvents = false;
   }
}

private void processMyXyEvent(...) {
   if (ignoreEvents) {
      return;
   }

   // listener code
}


I think the methods you implement are the closest you can get to a clean way of doing what you're looking for. And while I understand the requirement is taken for granted, it might be worth noting that by avoiding all the set listeners (specifically, ALL of them, not just the ones you were setting up yourself), you might end up driving the state of your application to something that is internally inconsistent.

I suppose what I'm saying is you should proceed with care :)

0

精彩评论

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