Posted on 2008-05-22 22:42
zht 閱讀(4933)
評論(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)換行,顏色以及其它屬性