在 Java Swing 開發中,工具提示預設由滑鼠懸停自動觸發。但在某些情境下(如按鈕點擊、表單驗證失敗、特定業務邏輯),開發者需要以程式碼主動控制 ToolTip 的顯示與隱藏。本文將深入解析 Swing 內部機制,並提供可直接使用的靜態工具方法。
Swing 組件的 ToolTip 行為由 ToolTipManager 統一管理。當呼叫 setToolTipText(String) 時,若文字非空,ToolTipManager.sharedInstance() 會向該組件註冊兩個 Action:
這兩個 Action 被放入組件的 ActionMap 中,鍵值分別為 "postTip" 與 "hideTip"。我們只需從 ActionMap 取出對應 Action,並構造一個 ActionEvent 觸發 actionPerformed,即可程式化控制 ToolTip。
public static void postToolTip(JComponent comp) {
Action action = comp.getActionMap().get("postTip");
if (action == null) return; // 該組件未設定 ToolTip
ActionEvent ae = new ActionEvent(
comp,
ActionEvent.ACTION_PERFORMED,
"postTip",
EventQueue.getMostRecentEventTime(),
0
);
action.actionPerformed(ae);
}
public static void hideToolTip(JComponent comp) {
Action action = comp.getActionMap().get("hideTip");
if (action == null) return;
ActionEvent ae = new ActionEvent(
comp,
ActionEvent.ACTION_PERFORMED,
"hideTip",
EventQueue.getMostRecentEventTime(),
0
);
action.actionPerformed(ae);
}
下列程式碼示範:點擊「按鈕 A」顯示「按鈕 B」的 ToolTip,反之亦然。
public static void main(String[] args) {
JPanel panel = new JPanel();
JButton btnA = new JButton("按鈕 A");
btnA.setToolTipText("這是按鈕 A 的提示");
JButton btnB = new JButton("按鈕 B");
btnB.setToolTipText("這是按鈕 B 的提示");
panel.add(btnA);
panel.add(btnB);
btnA.addActionListener(e -> postToolTip(btnB));
btnB.addActionListener(e -> postToolTip(btnA));
JFrame frame = new JFrame("ToolTip 程式化控制示範");
frame.setContentPane(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
ToolTipManager 提供多項設定方法,可調整 ToolTip 行為:
setInitialDelay(int ms):首次顯示前等待毫秒數(預設 750)setReshowDelay(int ms):切換組件時的再次顯示延遲(預設 500)setDismissDelay(int ms):自動隱藏前的停留時間(預設 4000)範例:ToolTipManager.sharedInstance().setInitialDelay(200);
setToolTipText(...) 的組件有效。SwingUtilities.invokeLater 包裝。JToolTip 並覆寫 createToolTip()。透過存取組件 ActionMap 中的 "postTip" 與 "hideTip" Action,我們能輕鬆實現 ToolTip 的程式化顯示與隱藏,滿足非滑鼠懸停觸發的業務需求。搭配 ToolTipManager 的延遲參數微調,即可打造更靈活的使用者介面體驗。