Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
   *
   * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
   * Other names may be trademarks of their respective owners.
   *
   * The contents of this file are subject to the terms of either the GNU
  * General Public License Version 2 only ("GPL") or the Common
  * Development and Distribution License("CDDL") (collectively, the
  * "License"). You may not use this file except in compliance with the
  * License. You can obtain a copy of the License at
  * http://www.netbeans.org/cddl-gplv2.html
  * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
  * specific language governing permissions and limitations under the
  * License.  When distributing the software, include this License Header
  * Notice in each file and include the License file at
  * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
  * particular file as subject to the "Classpath" exception as provided
  * by Oracle in the GPL Version 2 section of the License file that
  * accompanied this code. If applicable, add the following below the
  * License Header, with the fields enclosed by brackets [] replaced by
  * your own identifying information:
  * "Portions Copyrighted [year] [name of copyright owner]"
  *
  * Contributor(s):
  *
  * The Original Software is NetBeans. The Initial Developer of the Original
  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
  * Microsystems, Inc. All Rights Reserved.
  *
  * If you wish your version of this file to be governed by only the CDDL
  * or only the GPL Version 2, indicate your decision by adding
  * "[Contributor] elects to include this software in this distribution
  * under the [CDDL or GPL Version 2] license." If you do not indicate a
  * single choice of license, a recipient has the option to distribute
  * your version of this file under either the CDDL, the GPL Version 2 or
  * to extend the choice of license to its licensees as provided above.
  * However, if you add GPL Version 2 code and therefore, elected the GPL
  * Version 2 license, then the option applies only if the new code is
  * made subject to such option by the copyright holder.
  */
 
 package org.netbeans.modules.java.navigation;
 
 import java.awt.*;
Customized copy of javax.swing.ToolTipManager

Author(s):
S. Aubrecht
 
 final class ToolTipManagerEx extends MouseAdapter implements MouseMotionListenerCallable<Boolean>  {
     
     private static final Logger LOG = Logger.getLogger(ToolTipManagerEx.class.getName());
     private static final RequestProcessor RP = new RequestProcessor(ToolTipManagerEx.class.getName(), 1, falsefalse);
     
     private Timer enterTimer;
     private Timer  exitTimer;
     private String toolTipText;
     private JComponent insideComponent;
     private MouseEvent mouseEvent;
     private boolean showImmediately;
     private transient Popup tipWindow;
     private volatile boolean cancelled;
    
The Window tip is being displayed in. This will be non-null if the Window tip is in differs from that of insideComponent's Window.
 
     private Window window;
     private ToolTipEx tip;
 
     private Rectangle popupRect = null;
 
    boolean enabled = true;
    private boolean tipShowing = false;
   
    private ToolTipProvider provider;
    
    private static final String WAITING_TEXT = NbBundle.getMessageToolTipManagerEx.class"LBL_PleaseWait" ); //NOI18N
    
    private AWTEventListener awtListener;
    
    
holds last object for which the tooltip was built
    private Rectangle lastTooltipForRect;
    private String lastTooltipText;
    
task that calculates tooltip
    private RequestProcessor.Task tooltipTask;
    
data lock for tooltip calculations
    private static final Object TOOLTIP_DATA_LOCK = new Object();
    static interface ToolTipProvider {
        JComponent getComponent();
        
        String getToolTipTextPoint loc );
        
        Rectangle getToolTipSourceBoundsPoint loc );
        
        Point getToolTipLocationPoint mouseLocationDimension toolTipSize );
        
        void invokeUserActionMouseEvent me );
    }
    
    public ToolTipManagerExToolTipProvider provider ) {
        assert null != provider;
        this. = provider;
        
         = new Timer(750, new insideTimerAction());
        .setRepeats(false);
         = new Timer(500, new outsideTimerAction());
        .setRepeats(false);
        
        registerComponentprovider.getComponent() );
    }

    
Enables or disables the tooltip.

Parameters:
flag true to enable the tip, false otherwise
    public void setEnabled(boolean flag) {
         = flag;
        if (!flag) {
            hideTipWindow();
        }
    }

    
Returns true if this object is enabled.

Returns:
true if this object is enabled, false otherwise
    public boolean isEnabled() {
        return ;
    }


    
Specifies the initial delay value.

Parameters:
milliseconds the number of milliseconds to delay (after the cursor has paused) before displaying the tooltip
See also:
getInitialDelay()
    public void setInitialDelay(int milliseconds) {
        .setInitialDelay(milliseconds);
    }

    
Returns the initial delay value.

Returns:
an integer representing the initial delay value, in milliseconds
See also:
setInitialDelay(int)
    public int getInitialDelay() {
        return .getInitialDelay();
    }

    
Used to specify the amount of time before the user has to wait initialDelay milliseconds before a tooltip will be shown. That is, if the tooltip is hidden, and the user moves into a region of the same Component that has a valid tooltip within milliseconds milliseconds the tooltip will immediately be shown. Otherwise, if the user moves into a region with a valid tooltip after milliseconds milliseconds, the user will have to wait an additional initialDelay milliseconds before the tooltip is shown again.

Parameters:
milliseconds time in milliseconds
See also:
getReshowDelay()
    public void setReshowDelay(int milliseconds) {
        .setInitialDelay(milliseconds);
    }

    
Returns the reshow delay property.

Returns:
reshown delay property
See also:
setReshowDelay(int)
    public int getReshowDelay() {
        return .getInitialDelay();
    }
    
    @Override
    public Boolean call() throws Exception {
        return ;
    }
    protected void showTipWindow() {
        if( == null || !.isShowing())
            return;
         = false;
        .fine("cancelled=false");    //NOI18N
	for (Container p = .getParent(); p != nullp = p.getParent()) {
            if (p instanceof JPopupMenubreak;
	    if (p instanceof Window) {
		if (!((Window)p).isFocused()) {
		    return;
		}
		break;
	    }
	}
        if () {
            Dimension size;
            
            // Just to be paranoid
            hideTipWindow();
             = createToolTip();
            .setTipText();
            size = .getPreferredSize();
            Point location = .getToolTipLocation.getPoint(), size );
	    // we do not adjust x/y when using awt.Window tips
	    if ( == null){
		 = new Rectangle();
	    }
	    .setBoundslocation.xlocation.ysize.widthsize.height );
	    
            PopupFactory popupFactory = PopupFactory.getSharedInstance();
	     = popupFactory.getPopup(,
					      location.x,
					      location.y);
	    .show();
            Window componentWindow = SwingUtilities.windowForComponent(
                                                    );
             = SwingUtilities.windowForComponent();
            if ( != null &&  != componentWindow) {
                .addMouseListener(this);
            }
            else {
                 = null;
            }
	     = true;
        }
    }
    
    protected void hideTipWindow() {
        if ( != null) {
            if ( != null) {
                .removeMouseListener(this);
                 = null;
            }
             = true;
            .fine("cancelled=true");    //NOI18N
            .hide();
	     = null;
	     = false;
	    (.getUI()).uninstallUI();
             = null;
            ifnull !=  )
                Toolkit.getDefaultToolkit().removeAWTEventListenergetAWTListener() );
        }
    }
    
    // add keylistener here to trigger tip for access
    
Registers a component for tooltip management.

This will register key bindings to show and hide the tooltip text only if component has focus bindings. This is done so that components that are not normally focus traversable, such as JLabel, are not made focus traversable as a result of invoking this method.

Parameters:
component a JComponent object to add
See also:
java.awt.Component.isFocusTraversable()
    protected void registerComponent(JComponent component) {
        component.removeMouseListener(this);
        component.addMouseListener(this);
	if (shouldRegisterBindings(component)) {
	    // register our accessibility keybindings for this component
	    // this will apply globally across L&F
	    // Post Tip: Ctrl+F1
	    // Unpost Tip: Esc and Ctrl+F1
	    InputMap inputMap = component.getInputMap(.);
	    ActionMap actionMap = component.getActionMap();
	    if (inputMap != null && actionMap != null) {
                //XXX remove
	    }
	}
    }

    
Removes a component from tooltip control.

Parameters:
component a JComponent object to remove
    protected void unregisterComponent(JComponent component) {
        component.removeMouseListener(this);
	if (shouldRegisterBindings(component)) {
	    InputMap inputMap = component.getInputMap(.);
	    ActionMap actionMap = component.getActionMap();
	    if (inputMap != null && actionMap != null) {
                //XXX remove
	    }
	}
    }

    
Returns whether or not bindings should be registered on the given JComponent. This is implemented to return true if the tool tip manager has a binding in any one of the InputMaps registered under the condition WHEN_FOCUSED.

This does not use isFocusTraversable as some components may override isFocusTraversable and base the return value on something other than bindings. For example, JButton bases its return value on its enabled state.

Parameters:
component the JComponent in question
    private boolean shouldRegisterBindings(JComponent component) {
	InputMap inputMap = component.getInputMap(.);
	while (inputMap != null && inputMap.size() == 0) {
	    inputMap = inputMap.getParent();
	}
	return (inputMap != null);
    }
    // implements java.awt.event.MouseListener
    
Called when the mouse enters the region of a component. This determines whether the tool tip should be shown.

Parameters:
event the event in question
    public @Override void mouseEntered(MouseEvent event) {
        initiateToolTip(event);
    }
    private void initiateToolTip(MouseEvent event) {
        if (event.getSource() == ) {
            return;
        }
        JComponent component = (JComponent)event.getSource();
        .stop();
	Point location = event.getPoint();
	// ensure tooltip shows only in proper place
	if (location.x < 0 || 
	    location.x >=component.getWidth() ||
	    location.y < 0 ||
	    location.y >= component.getHeight()) {
	    return;
	}
        if ( != null) {
            .stop();
        }
	// A component in an unactive internal frame is sent two
	// mouseEntered events, make sure we don't end up adding
	// ourselves an extra time.
        component.removeMouseMotionListener(this);
        component.addMouseMotionListener(this);
        boolean sameComponent = ( == component);
         = component;
	if ( != null){
             = event;
            if () {
                Rectangle rect = .getToolTipSourceBoundsevent.getPoint() );
                ifnull != rect ) {
                    String newToolTipText = startToolTipCalculationrectevent.getPoint() );
                    if (!sameComponent || !.equals(newToolTipText/*|| 
                             !sameLoc*/) {
                         = newToolTipText;
                        showTipWindow();
                    }
                }
            } else {
                .start();
            }
        }
    }
    // implements java.awt.event.MouseListener
    
Called when the mouse exits the region of a component. Any tool tip showing should be hidden.

Parameters:
event the event in question
    public @Override void mouseExited(MouseEvent event) {
        boolean shouldHide = true;
        if ( == null) {
            // Drag exit
        } 
        else if ( != null && event.getSource() == ) {
	  // if we get an exit and have a heavy window
	  // we need to check if it if overlapping the inside component
            Container insideComponentWindow = .getTopLevelAncestor();
            if (insideComponentWindow != null) {
                Point location = event.getPoint();
                SwingUtilities.convertPointToScreen(location);
                location.x -= insideComponentWindow.getX();
                location.y -= insideComponentWindow.getY();
                location = SwingUtilities.convertPoint(null,location,);
                if (location.x >= 0 && location.x < .getWidth() &&
                   location.y >= 0 && location.y < .getHeight()) {
                    shouldHide = false;
                } else {
                    shouldHide = true;
                }
            }
        } else if(event.getSource() ==  &&  != null) {
	    Window win = SwingUtilities.getWindowAncestor();
	    if (win != null) {	// insideComponent may have been hidden (e.g. in a menu)
		Point location = SwingUtilities.convertPoint(,
							     event.getPoint(),
							     win);
		location.x += bounds.x;
		location.y += bounds.y;
		Point loc = new Point(0, 0);
		SwingUtilities.convertPointToScreen(loc);
		bounds.x = loc.x;
		bounds.y = loc.y;
		bounds.width = .getWidth();
		bounds.height = .getHeight();
// issue #158925, no need to preserve window if mouse entered in.
//		if (location.x >= bounds.x && location.x < (bounds.x + bounds.width) &&
//		    location.y >= bounds.y && location.y < (bounds.y + bounds.height)) {
//		    shouldHide = false;
//		} else {
		    shouldHide = true;
//		}
	    }
        } 
        
        if (shouldHide) {        
            .stop();
	    if ( != null) {
	    }
             = null;
             = null;
             = null;
            hideTipWindow();
            .restart();
        }
    }
    // implements java.awt.event.MouseListener
    
Called when the mouse is pressed. Any tool tip showing should be hidden.

Parameters:
event the event in question
    public @Override void mousePressed(MouseEvent event) {
        hideTipWindow();
        .stop();
         = false;
         = null;
         = null;
    }
    // implements java.awt.event.MouseMotionListener
    
Called when the mouse is pressed and dragged. Does nothing.

Parameters:
event the event in question
    public void mouseDragged(MouseEvent event) {
    }
    // implements java.awt.event.MouseMotionListener
    
Called when the mouse is moved. Determines whether the tool tip should be displayed.

Parameters:
event the event in question
    public void mouseMoved(MouseEvent event) {
        if () {
            checkForTipChange(event);
        }
        else if () {
            Rectangle rect = .getToolTipSourceBoundsevent.getPoint() );
            ifnull != rect ) {
                JComponent component = (JComponent)event.getSource();
                 = startToolTipCalculation(rectevent.getPoint());
                if ( != null) {
                     = event;
                     = component;
                    .stop();
                    showTipWindow();
                }
            }
        }
        else {
            // Lazily lookup the values from within insideTimerAction
             = (JComponent)event.getSource();
             = event;
             = null;
            .restart();
        }
    }

    
Checks to see if the tooltip needs to be changed in response to the MouseMoved event event.
    private void checkForTipChange(MouseEvent event) {
        JComponent component = (JComponent)event.getSource();
        Rectangle newRect = .getToolTipSourceBoundsevent.getPoint() );//component.getToolTipLocation(event);
        if ( newRect != null) {
             = event;
            if ( newRect.equals ) ) {
                if ( == null) {
                    .restart();
                }
            } else {
                 = startToolTipCalculation(newRectevent.getPoint());
                if () {
                    hideTipWindow();
                    showTipWindow();
                    .stop();
                } else {
                    .restart();
                }
            }
        } else {
             = null;
             = null;
             = null;
            hideTipWindow();
            .stop();
            .restart();
        }
    }
    protected class insideTimerAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if( != null && .isShowing()) {
                // Lazy lookup
                if ( == null &&  != null) {
                    Rectangle rect = .getToolTipSourceBounds.getPoint() );
                    ifnull != rect ) {
                         = startToolTipCalculation(rect.getPoint());
                    }
                }
                if( != null) {
                     = true;
                    showTipWindow();
                }
                else {
                     = null;
                     = null;
                     = null;
                    hideTipWindow();
                }
            }
        }
    }
    protected class outsideTimerAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
             = false;
        }
    }
  /* This listener is registered when the tooltip is first registered
   * on a component in order to catch the situation where the tooltip
   * was turned on while the mouse was already within the bounds of
   * the component.  This way, the tooltip will be initiated on a
   * mouse-entered or mouse-moved, whichever occurs first.  Once the
   * tooltip has been initiated, we can remove this listener and rely
   * solely on mouse-entered to initiate the tooltip.
   */
    private class MoveBeforeEnterListener extends MouseMotionAdapter {
        public @Override void mouseMoved(MouseEvent e) {
	    initiateToolTip(e);
	}
    }
    protected ToolTipEx createToolTip() {
        return new ToolTipEx();
    }
    
    protected AWTEventListener getAWTListener() {
        ifnull ==  ) {
             = new AWTEventListener() {
                boolean armed = false;
                public void eventDispatchedAWTEvent e ) {
                    ife instanceof KeyEvent ) {
                        KeyEvent ke = (KeyEvent)e;
                        ifke.getKeyCode() == . && (ke.isControlDown() || ke.isMetaDown()) ) {
                            ifke.getID() == . ) {
                                 = true;
                                return;
                            } else ifke.getID() == . &&  ) {
                                ke.consume();
                                 = false;
                                .invokeUserAction );
                                hideTipWindow();
                                return;
                            }
                        } else if( !(ke.getKeyCode() == . || ke.getKeyCode() == .) ) {
                             = false;
                        }
                    }
                }
            };
        }
        return ;
    }
    
    private String startToolTipCalculationRectangle tooltipForRectPoint loc ) {
        synchronized () {
            iftooltipForRect.equals ) ) {
                // no further activity, because tooltip is just being calculated or already displayed
                return ;
            }
            // cancel previous now invalid task
            if ( != null) {
                boolean cancelled = .cancel();
                 = null;
            }
             = new RectangletooltipForRect );
        }
        // start full tooltip calculation in request processor
        TooltipCalculator tc = new TooltipCalculatortooltipForRectloc );
        synchronized () {
             = .post(tc);
        }
        return ;
    }

    
calculates tooltip and invokes tooltip refresh
    private class TooltipCalculator implements Runnable {
        
        private Point location;
        private Rectangle tooltipForRect;
        
        TooltipCalculatorRectangle tooltipForRectPoint loc ) {
            this. = tooltipForRect;
            this. = loc;
        }
        
        
actually calculates tooltip for given item
        public void run () {
            final String result = .getToolTipText );
            ifnull == result )
                return;
            
            synchronized () {
                 = null;
                // cancel if not needed (tooltip for another object was requested later)
                if == null || !.equals ) ) {
                    return;
                }
                 = result;
            }
            // invoke tooltip
            SwingUtilities.invokeLater(new Runnable () {
                public void run () {
                     = result;
                    ifnull !=  ) {
                        .setTipText();
                        .invalidate();
                        .revalidate();
                        .repaint();
                    }
                }
            });
        }
    }
    
    private Dimension getDefaultToolTipSize() {
        Preferences prefs = MimeLookup.getLookup(.).lookup(Preferences.class);
        String size = prefs.get(.null);
        Dimension dim = size == null ? null : parseDimension(size);
        return dim != null ? dim : new Dimension(500,300);
    }
    
    private static Dimension parseDimension(String s) {
        StringTokenizer st = new StringTokenizer(s","); // NOI18N
        int arr[] = new int[2];
        int i = 0;
        while (st.hasMoreElements()) {
            if (i > 1) {
                return null;
            }
            try {
                arr[i] = Integer.parseInt(st.nextToken());
            } catch (NumberFormatException nfe) {
                .log(.nullnfe);
                return null;
            }
            i++;
        }
        if (i != 2) {
            return null;
        } else {
            return new Dimension(arr[0], arr[1]);
        }
    }
    
    private class ToolTipEx extends JPanel {
        private HTMLDocView content;
        private JLabel shortcut;
        public ToolTipEx() {
            supernew GridBagLayout() );
            setPreferredSizegetDefaultToolTipSize() );
            // Color background = getDefaultToolTipBackground();
            
            Color background = new JEditorPane().getBackground();
            background = new Color(
                    Math.max(background.getRed() - 8, 0 ), 
                    Math.max(background.getGreen() - 8, 0 ), 
                    background.getBlue());
            
            setBackgroundbackground );
             = new HTMLDocViewbackground );
            JScrollPane scroll = new JScrollPane );
            addscrollnew GridBagConstraints(0,0,1,1,1.0,1.0,.,.,new Insets(0,0,0,0),0,0) );
             = new JLabel( NbBundle.getMessageToolTipManagerEx.class"HINT_EnlargeJavaDocToolip"//NOI18N
                    Utilities.isMac() ? KeyEvent.getKeyText(.)+"+F1" : "Ctrl+F1" ) ); //NOI18N //NOI18N
            .setHorizontalAlignment. );
            .setBorder( BorderFactory.createLineBorder(.) );
            addnew GridBagConstraints(0,1,1,1,0.0,0.0,.,.,new Insets(0,0,0,0),0,0) );
        }
        public void setTipText(String text) {
            if.equals(text) ) {
                .setContentnull );
                .setVisiblefalse );
            } else {
                .setContenttextnull );
                .setVisibletrue );
            }
        }
    }