Our Java product has a main JToolBar
where, from a certain point onwards, a couple of background Threads can add new JButtons, starting from the extreme right, as alarms, according to some met conditions during their routines.
So, our main frame has a private attribute like this:
private final Component featuresHorizontalGlue = Box.createHorizontalGlue();
and when alarm Threads refresh, they firstly call
private synchronized void manageHorizontalGlue(boolean toBeAdded) {
if (toBeAdded) {
if (SwingUtilities.getAncestorOfClass(toolbar.getClass(), featuresHorizontalGlue) == null) {
logger.debug("Adding Horizontal Glue to main ToolBar");
toolbar.toolbar.add(featuresHorizontalGlue);
}
}
}
as the HorizontalGlue
component should be unique, so that each following added alarm button will be right aligned.
A similar method is called when alarm buttons are added for the first time in the toolbar, then they are simply refreshed in their icons.
Anyway, an ex colleague of mine implemented some methods where, if some other conditions are met, main toolbar is completely disposed and recreated.
And so, I expected that my alarm methods worked fine but they do not because even if a new constructor is called on toolbar
, then getAncestorOfClass()
returns not null and so horizontal glue and alarm buttons are not re-added and showed anymore.
Why this?
If I inspect with debug on Eclipse the Components[]
array inside toolbar, I cannot see anymore those buttons and HorizontalGlue
component. So, why does that method not return null?
Apparently you misunderstood the purpose of this method, which is strange, as its name “getAncestorOfClass
” clearly indicates that it will return an ancestor having a matching class, not necessarily the instance, you have in mind. If that’s not enough, you are passing toolbar.getClass()
to it, not the toolbar
instance. So it even couldn’t check whether it is the same instance; it will simply return any ancestor JToolBar
instance, if there is one, e.g. the old toolbar.
In the end, if you want to know whether toolbar
is an ancestor of featuresHorizontalGlue
, you can test it straight-forwardly using toolBar.isAncestorOf(featuresHorizontalGlue)
. No need to look into any extra utility class.
Besides that, when I read “a couple of background Threads can add new JButtons”, I hope, you have read and understood Swing’s Threading Policy…