Swing


天行健 君子以自强不息

posts - 69, comments - 215, trackbacks - 0, articles - 16
   :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

控制Swing中ToolTip的显示与隐藏

Posted on 2008-05-22 22:42 zht 阅读(4891) 评论(4)  编辑  收藏 所属分类: Swing

 

先给出两个控制方法
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 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的显示与隐藏。

对于tooltip的显示时间可以通过ToolTipManager中的set**的方法进行设置。


以下是测试代码

    public static void main(String[] args) {
        
final JPanel panel = new JPanel();
        
final JButton btn = new JButton("button");
        btn.setToolTipText(
"button_tooltip");
        panel.add(btn);
        
final JButton btn1 = new JButton("button1");
        panel.add(btn1);
        btn1.setToolTipText(
"button1_tooltip");
        btn.addActionListener(
new ActionListener() {
            
public void actionPerformed(ActionEvent e) {
                postToolTip(btn1);

            }
        });
        btn1.addActionListener(
new ActionListener() {
            
public void actionPerformed(ActionEvent e) {
                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);
    }



注:以上有些内容引用自网络,我加了一些个人理解。

下一篇将介绍一下对tooltip显示的控制,ex)换行,颜色以及其它属性