首页 / 软件开发 / JAVA / 控制Swing中ToolTip的显示与隐藏
控制Swing中ToolTip的显示与隐藏2011-06-11 BlogJava zht先给出两个控制方法1、显示tooltippublic static void postToolTip(JComponent comp) {
Action action = comp.getActionMap().get("postTip");
if (action == null) // no tooltip
return;
ActionEvent ae = new ActionEvent(comp, ActionEvent.ACTION_PERFORMED, "postTip", EventQueue.getMostRecentEventTime(), 0);
action.actionPerformed(ae);
}2、隐藏tooltippublic static void hideToolTip(JComponent comp) {
Action action = comp.getActionMap().get("hideTip");
if (action == null) // no tooltip
return;
ActionEvent ae = new ActionEvent(comp, ActionEvent.ACTION_PERFORMED, "hideTip", EventQueue.getMostRecentEventTime(), 0);
action.actionPerformed(ae);
}tooltip的显示与隐藏都是通过ToolTipManager这个类来控制的当componet.setToolTipText的时候java的内部处理为public void setToolTipText(String text) {
String oldText = getToolTipText();
putClientProperty(TOOL_TIP_TEXT_KEY, text);
ToolTipManager toolTipManager = ToolTipManager.sharedInstance ();
if (text != null) {
if (oldText == null) {
toolTipManager.registerComponent(this);
}
} else {
toolTipManager.unregisterComponent(this);
}
}而在ToolTipManager 的registerComponent方法中将两个Action添加到了组 件的actionMap 中,具体的acton实现可以参考ToolTipManager 。ActionMap actionMap = component.getActionMap();
if (inputMap != null && actionMap != null) {
actionMap.put("postTip", postTipAction);
actionMap.put("hideTip", hideTipAction);上述两个方法就是取得这两个Action,然后调用相应的Action方法来控制 tooltip的显示与隐藏。