题
是否有在Swing的elegantish的方式,以找出是否有目前在我的框架中显示?任何提示
我使用的是自定义工具提示,所以这将是很容易设置一个标志,在我createToolTip()
方法,但我不能看到一个办法,找出当提示也没有了。
ToolTipManager
有这个,tipShowing一个很好的标志,当然这是private
,他们似乎并没有提供一种方式来获得它。 hideWindow()
不调出该工具提示组件(即我可以告诉),所以我看不出有什么办法。
任何人有任何好的想法?
更新:我与反射去。你可以在这里看到的代码:
private boolean isToolTipVisible() {
// Going to do some nasty reflection to get at this private field. Don't try this at home!
ToolTipManager ttManager = ToolTipManager.sharedInstance();
try {
Field f = ttManager.getClass().getDeclaredField("tipShowing");
f.setAccessible(true);
boolean tipShowing = f.getBoolean(ttManager);
return tipShowing;
} catch (Exception e) {
// We'll keep silent about this for now, but obviously we don't want to hit this
// e.printStackTrace();
return false;
}
}
解决方案
看来,hideTipAction的的IsEnabled()属性被直接连到tipShowing布尔值。你可以试试这个:
public boolean isTooltipShowing(JComponent component) {
AbstractAction hideTipAction = (AbstractAction) component.getActionMap().get("hideTip");
return hideTipAction.isEnabled();
}
您可能想要做一些理智检查空值,等等。但是这应该让你非常接近。
EDIT,到您的回答:
这是一些丑陋的反射代码短,我不认为你有太多的选择。你不能子类ToolTipManager
因为包私有构造函数,并且showTipWindow()
和hideTipWindow()
也包专用,因此适配器模式是出来为好。
其他提示
它看起来就像是将需要遍历所有的部件,看看他们是否有一个提示。我在寻找一个全球性的价值。这可能是一个循环是可行的,但似乎没有效率。
这太糟糕了。内部讨论之后,“丑陋的反思”是什么,我们想出了为好,但我希望有人在那里有一个更好的主意。
既然你已经有自己的createToolTip(),也许你可以尝试这样的事:)
public JToolTip createToolTip() {
JToolTip tip = super.createToolTip();
tip.addAncestorListener( new AncestorListener() {
public void ancestorAdded( AncestorEvent event ) {
System.out.println( "I'm Visible!..." );
}
public void ancestorRemoved( AncestorEvent event ) {
System.out.println( "...now I'm not." );
}
public void ancestorMoved( AncestorEvent event ) {
// ignore
}
} );
return tip;
}
不隶属于 StackOverflow