2008-12-01 45 views
3

在Swing中是否有一种优雅的方式来确定当前是否在我的框架中显示了任何工具提示?可以摆动告诉我,如果有一个活跃的工具提示?

我正在使用自定义工具提示,所以在我的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; 
    } 
} 

回答

3

看起来hideTipAction的isEnabled()属性直接绑定到tipShowing布尔值。你可以试试这个:

public boolean isTooltipShowing(JComponent component) { 
    AbstractAction hideTipAction = (AbstractAction) component.getActionMap().get("hideTip"); 
    return hideTipAction.isEnabled(); 
} 

你可能想对空值等进行一些理智的检查,但是这应该会让你非常接近。

编辑,你的对策:

的一些丑陋的反射代码短,我不认为你有太多的选择。由于包私有构造函数,您不能继承ToolTipManager,并且showTipWindow()hideTipWindow()也是包私有的,所以适配器模式也是如此。

0

它看起来像要循环所有的组件看他们是否有工具提示。我正在寻找全球价值。这可能是一个循环是可行的,但它似乎效率低下。

0

这太糟糕了。经过内部讨论后,我们提出了“丑陋的反思”,但我希望有人有更好的主意。

0

既然你已经有自己的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; 
} 
相关问题