java settooltip_控制Swing中的ToolTip的显示与隐藏 | 学步园

先给出两个控制方法

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);

}

转自http://java.csdn.net/page/845c9db3-0d64-4a3e-980e-20ee5cf87519

原作者

villa123

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值