先给出两个控制方法
1、显示tooltip
public 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、隐藏tooltip
public 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 ldText = 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的显示与隐藏。
对于tooltip的显示时间可以通过ToolTipManager中的set**的方法进行设置 。
以下是测试代码
publicstaticvoidmain(String[]args){ finalJPanelpanel=newJPanel(); finalJButtonbtn=newJButton("button"); btn.setToolTipText("button_tooltip"); panel.add(btn); finalJButtonbtn1=newJButton("button1"); panel.add(btn1); btn1.setToolTipText("button1_tooltip"); btn.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ postToolTip(btn1); } }); btn1.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ postToolTip(btn); } });JFrame. frame. = new JFrame(); frame.setContentPane(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(500, 400); frame.setLocationRelativeTo(null); frame.setVisible(true); }
注:以上有些内容引用自网络,我加了一些个人理解。
车到山前必有路,没路可以先开路,开路就得有乐观,