Set the Tooltip Delay Time for a Particular Compon

2020-02-24 11:59发布

问题:

I'm trying to set tooltips on a JEditorPane. The method which I use to determine what tooltip text to show is fairly CPU intensive - and so I would like to only show it after the mouse has stopped for a short amount of time - say 1 second.

I know I can use ToolTipManager.sharedInstance().setInitialDelay(), however this will set the delay time for tooltips on all swing components at once and I don't want this.

回答1:

Well, I would recommend doing the CPU intensive task on another thread so it doesn't interrupt normal GUI tasks.

That would be a better solution. (instead of trying to circumvent the problem)

*Edit* You could possibly calculate the tootips for every word in the JEditorPane and store them in a Map. Then all you would have to do is access the tootip out of the Map if it changes.

Ideally people won't be moving the mouse and typing at the same time. So, you can calculate the tootlips when the text changes, and just pull them from the Map on mouseMoved().



回答2:

If what you want is to make the tooltip dismiss delay much longer for a specific component, then this is a nice hack:

(kudos to tech at http://tech.chitgoks.com/2010/05/31/disable-tooltip-delay-in-java-swing/)

private final int defaultDismissTimeout = ToolTipManager.sharedInstance().getDismissDelay();

addMouseListener(new MouseAdapter() {

  public void mouseEntered(MouseEvent me) {
    ToolTipManager.sharedInstance().setDismissDelay(60000);
  }

  public void mouseExited(MouseEvent me) {
    ToolTipManager.sharedInstance().setDismissDelay(defaultDismissTimeout);
  }
});


回答3:

You can show the popup yourself. Listen for mouseMoved() events, start/stop the timer and then show popup with the following code:

First you need PopupFactory, Popup, and ToolTip:

private PopupFactory popupFactory = PopupFactory.getSharedInstance();
private Popup popup;
private JToolTip toolTip = jEditorPane.createToolTip();

then, to show or hide the toolTip:

private void showToolTip(MouseEvent e) {
    toolTip.setTipText(...);
    int x = e.getXOnScreen();
    int y = e.getYOnScreen();
    popup = popupFactory.getPopup(jEditorPane, toolTip, x, y);
    popup.show();
}

private void hideToolTip() {
    if (popup != null)
        popup.hide();
}

This will give you adjustable delay and a lot of troubles :)