javax.swing.JToolTip Java Examples

The following examples show how to use javax.swing.JToolTip. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SeaGlassToolTipUI.java    From seaglass with Apache License 2.0 6 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
public Dimension getPreferredSize(JComponent c) {
    SeaGlassContext context = getContext(c);
    Insets insets = c.getInsets();
    Dimension prefSize = new Dimension(insets.left + insets.right, insets.top + insets.bottom);
    String text = ((JToolTip) c).getTipText();

    if (text != null) {
        View v = (c != null) ? (View) c.getClientProperty("html") : null;
        if (v != null) {
            prefSize.width += (int) v.getPreferredSpan(View.X_AXIS);
            prefSize.height += (int) v.getPreferredSpan(View.Y_AXIS);
        } else {
            Font font = context.getStyle().getFont(context);
            FontMetrics fm = c.getFontMetrics(font);
            prefSize.width += context.getStyle().getGraphicsUtils(context).computeStringWidth(context, font, fm, text);
            prefSize.height += fm.getHeight();
        }
    }
    context.dispose();
    return prefSize;
}
 
Example #2
Source File: CustomPopupFactory.java    From WorldGrower with GNU General Public License v3.0 6 votes vote down vote up
public static void setPopupFactory() {
	PopupFactory.setSharedInstance(new PopupFactory() {

		@Override
		public Popup getPopup(Component owner, Component contents, int x, int y) throws IllegalArgumentException {
			if (contents instanceof JToolTip) {
				JToolTip toolTip = (JToolTip)contents;
				int width = (int) toolTip.getPreferredSize().getWidth();
				
				GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
				int screenWidth = gd.getDisplayMode().getWidth();
				
				// if there is enough room, move tooltip to the right to have enough room
				// for large tooltips.
				// this way they don't hinder mouse movement and make it possible to easily
				// view multiple tooltips of items.
				if (x + width + TOOLTIP_X_OFFSET < screenWidth) {
					x += TOOLTIP_X_OFFSET;
				}
			}
			return super.getPopup(owner, contents, x, y);
		}
	});
}
 
Example #3
Source File: MultiLineToolTipUI.java    From mzmine2 with GNU General Public License v2.0 6 votes vote down vote up
public Dimension getPreferredSize(JComponent c) {
  Font font = c.getFont();
  String tipText = ((JToolTip) c).getTipText();
  JToolTip mtt = (JToolTip) c;
  FontMetrics fontMetrics = mtt.getFontMetrics(font);
  int fontHeight = fontMetrics.getHeight();

  if (tipText == null)
    return new Dimension(0, 0);

  String lines[] = tipText.split("\n");
  int num_lines = lines.length;

  int width, height, onewidth;
  height = num_lines * fontHeight;
  width = 0;
  for (int i = 0; i < num_lines; i++) {
    onewidth = fontMetrics.stringWidth(lines[i]);
    width = Math.max(width, onewidth);
  }
  return new Dimension(width + inset * 2, height + inset * 2);
}
 
Example #4
Source File: ShowcaseDemo.java    From pumpernickel with MIT License 6 votes vote down vote up
/**
 * Add a popover labeling a slider.
 * 
 * @param suffix
 *            the text to append after the numeric value, such as "%" or
 *            " pixels".
 */
protected void addSliderPopover(JSlider slider, final String suffix) {
	JPopover p = new JPopover<JToolTip>(slider, new JToolTip(), false) {

		@Override
		protected void doRefreshPopup() {
			JSlider js = (JSlider) getOwner();
			int v = js.getValue();
			String newText;
			if (v == 1 && suffix.startsWith(" ") && suffix.endsWith("s")) {
				newText = v + suffix.substring(0, suffix.length() - 1);
			} else {
				newText = v + suffix;
			}
			getContents().setTipText(newText);

			// this is only because we have the JToolTipDemo so
			// colors might change:
			getContents().updateUI();
			getContents().setBorder(null);
		}
	};
	p.setTarget(new SliderThumbPopupTarget(slider));
}
 
Example #5
Source File: JComponentOperator.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public JToolTipWindowFinder() {
    ppFinder = new ComponentChooser() {
        @Override
        public boolean checkComponent(Component comp) {
            return (comp.isShowing()
                    && comp.isVisible()
                    && comp instanceof JToolTip);
        }

        @Override
        public String getDescription() {
            return "A tool tip";
        }

        @Override
        public String toString() {
            return "JComponentOperator.JToolTipWindowFinder.ComponentChooser{description = " + getDescription() + '}';
        }
    };
}
 
Example #6
Source File: SeaGlassToolTipUI.java    From seaglass with Apache License 2.0 6 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
public void propertyChange(PropertyChangeEvent e) {
    if (SeaGlassLookAndFeel.shouldUpdateStyle(e)) {
        updateStyle((JToolTip) e.getSource());
    }
    String name = e.getPropertyName();
    if (name.equals("tiptext") || "font".equals(name) || "foreground".equals(name)) {
        // remove the old html view client property if one
        // existed, and install a new one if the text installed
        // into the JLabel is html source.
        JToolTip tip = ((JToolTip) e.getSource());
        String text = tip.getTipText();
        BasicHTML.updateRenderer(tip, text);
    }
}
 
Example #7
Source File: CounterRequestTable.java    From javamelody with Apache License 2.0 6 votes vote down vote up
@Override
public void paint(Graphics g, JComponent c) {
	try {
		final String tipText = ((JToolTip) c).getTipText();
		final BufferedImage image = getRequestChartByRequestName(tipText);
		// on affiche que l'image et pas le text dans le tooltip
		//		    FontMetrics metrics = c.getFontMetrics(g.getFont());
		//		    g.setColor(c.getForeground());
		//		    g.drawString(tipText, 1, 1);
		if (image != null) {
			g.drawImage(image, 0, 0, c);
		} else {
			super.paint(g, c);
		}
	} catch (final IOException e) {
		// s'il y a une erreur dans la récupération de l'image tant pis
		super.paint(g, c);
	}
}
 
Example #8
Source File: Outline.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public JToolTip createToolTip() {
    JToolTip t = toolTip;
    toolTip = null;
    if (t != null) {
        t.addMouseMotionListener(new MouseMotionAdapter() { // #233642

            boolean initialized = false;

            @Override
            public void mouseMoved(MouseEvent e) {
                if (!initialized) {
                    initialized = true; // ignore the first event
                } else {
                    // hide the tooltip if mouse moves over it
                    ToolTipManager.sharedInstance().mousePressed(e);
                }
            }
        });
        return t;
    } else {
        return super.createToolTip();
    }
}
 
Example #9
Source File: AbstractReferenceHover.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * initializeLazily() should get called to try to get the CodeFormatService and create the panel
 * the first time we want to use the panel.
 */
protected void initializeLazily() {
	if (panel != null) {
		return;
	}
	if (tool == null) {
		return;
	}
	if (codeFormatService == null) {
		codeFormatService = tool.getService(CodeFormatService.class);
	}
	if (codeFormatService == null) {
		return;
	}

	panel = new ListingPanel(codeFormatService.getFormatManager());// share the manager from the code viewer
	panel.setTextBackgroundColor(BACKGROUND_COLOR);

	toolTip = new JToolTip();
}
 
Example #10
Source File: TooltipImageTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String PATH = TooltipImageTest.class.getResource("circle.png").getPath();
    SwingUtilities.invokeAndWait(() -> {
        JToolTip tip = new JToolTip();
        tip.setTipText("<html><img width=\"100\" src=\"file:///" + PATH + "\"></html>");
        checkSize(tip, 100, 100);

        tip.setTipText("<html><img height=\"100\" src=\"file:///" + PATH + "\"></html>");
        checkSize(tip, 100, 100);

        tip.setTipText("<html><img src=\"file:///" + PATH + "\"></html>");
        checkSize(tip, 200, 200);

        tip.setTipText("<html><img width=\"50\" src=\"file:///" + PATH + "\"></html>");
        checkSize(tip, 50, 50);

        tip.setTipText("<html><img height=\"50\" src=\"file:///" + PATH + "\"></html>");
        checkSize(tip, 50, 50);

        tip.setTipText("<html><img width=\"100\" height=\"50\" src=\"file:///" + PATH + "\"></html>");
        checkSize(tip, 100, 50);
    });

    System.out.println("Test case passed.");
}
 
Example #11
Source File: SeaGlassToolTipUI.java    From seaglass with Apache License 2.0 6 votes vote down vote up
/**
 * Paints the specified component.
 *
 * @param context
 *            context for the component being painted
 * @param g
 *            the {@code Graphics} object used for painting
 * @see #update(Graphics,JComponent)
 */
protected void paint(SynthContext context, Graphics g) {
    JToolTip tip = (JToolTip) context.getComponent();

    Insets insets = tip.getInsets();
    View v = (View) tip.getClientProperty(BasicHTML.propertyKey);
    if (v != null) {
        Rectangle paintTextR = new Rectangle(insets.left, insets.top, tip.getWidth() - (insets.left + insets.right), tip.getHeight()
                - (insets.top + insets.bottom));
        v.paint(g, paintTextR);
    } else {
        g.setColor(context.getStyle().getColor(context, ColorType.TEXT_FOREGROUND));
        g.setFont(style.getFont(context));
        context.getStyle().getGraphicsUtils(context).paintText(context, g, tip.getTipText(), insets.left, insets.top, -1);
    }
}
 
Example #12
Source File: MultiLineToolTipUI.java    From mzmine2 with GNU General Public License v2.0 6 votes vote down vote up
public void paint(Graphics g, JComponent c) {
  Font font = c.getFont();
  JToolTip mtt = (JToolTip) c;
  FontMetrics fontMetrics = mtt.getFontMetrics(font);
  Dimension dimension = c.getSize();
  int fontHeight = fontMetrics.getHeight();
  int fontAscent = fontMetrics.getAscent();
  String tipText = ((JToolTip) c).getTipText();
  if (tipText == null)
    return;
  String lines[] = tipText.split("\n");
  int num_lines = lines.length;
  int height;
  int i;

  g.setColor(c.getBackground());
  g.fillRect(0, 0, dimension.width, dimension.height);
  g.setColor(c.getForeground());
  for (i = 0, height = 2 + fontAscent; i < num_lines; i++, height += fontHeight) {
    g.drawString(lines[i], inset, height);
  }
}
 
Example #13
Source File: FlatToolTipUI.java    From FlatLaf with Apache License 2.0 6 votes vote down vote up
@Override
public void paint( Graphics g, JComponent c ) {
	if( isMultiLine( c ) ) {
		FontMetrics fm = c.getFontMetrics( c.getFont() );
		Insets insets = c.getInsets();

		FlatUIUtils.setRenderingHints( (Graphics2D) g );
		g.setColor( c.getForeground() );

		List<String> lines = StringUtils.split( ((JToolTip)c).getTipText(), '\n' );

		int x = insets.left + 3;
		int x2 = c.getWidth() - insets.right - 3;
		int y = insets.top - fm.getDescent();
		int lineHeight = fm.getHeight();
		JComponent comp = ((JToolTip)c).getComponent();
		boolean leftToRight = (comp != null ? comp : c).getComponentOrientation().isLeftToRight();
		for( String line : lines ) {
			y += lineHeight;
			FlatUIUtils.drawString( c, g, line, leftToRight ? x : x2 - SwingUtilities.computeStringWidth( fm, line ), y );
		}
	} else
		super.paint( HiDPIUtils.createGraphicsTextYCorrection( (Graphics2D) g ), c );
}
 
Example #14
Source File: LibraryTreePanel.java    From osp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates the tree.
 * 
 * @param root the root node
 */
protected void createTree(LibraryTreeNode root) {
  treeModel = new DefaultTreeModel(root);
  tree = new JTree(treeModel) {
  	public JToolTip createToolTip() {
  		return new JMultiLineToolTip();
  	}
  };
  if (root.createChildNodes()) {
   LibraryTreeNode lastNode = (LibraryTreeNode)root.getLastChild();
 	TreePath path = new TreePath(lastNode.getPath());
 	tree.scrollPathToVisible(path);
  }
  treeNodeRenderer = new LibraryTreeNodeRenderer();
  tree.setCellRenderer(treeNodeRenderer);
  tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
  ToolTipManager.sharedInstance().registerComponent(tree);
  // listen for tree selections and display the contents
  tree.addTreeSelectionListener(treeSelectionListener);
  // listen for mouse events to display node info and inform propertyChangeListeners
  tree.addMouseListener(treeMouseListener);
  // put tree in scroller
  treeScroller.setViewportView(tree);
}
 
Example #15
Source File: FlatToolTipUI.java    From FlatLaf with Apache License 2.0 6 votes vote down vote up
@Override
protected void installListeners( JComponent c ) {
	super.installListeners( c );

	if( sharedPropertyChangedListener == null ) {
		sharedPropertyChangedListener = e -> {
			String name = e.getPropertyName();
			if( name == "text" || name == "font" || name == "foreground" ) {
				JToolTip toolTip = (JToolTip) e.getSource();
				FlatLabelUI.updateHTMLRenderer( toolTip, toolTip.getTipText(), false );
			}
		};
	}

	c.addPropertyChangeListener( sharedPropertyChangedListener );
}
 
Example #16
Source File: WelcomePanel.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
Paragraph(String text, String caption, int captionSizeDiff, Color background) {
    setCaret(new NoCaret());
    setShowPopup(false);
    setBackground(background);
    if (UIUtils.isNimbus()) setOpaque(false);
    
    setFocusable(false);
    
    setFont(new JToolTip().getFont());
    setText(setupText(text, caption, captionSizeDiff));
}
 
Example #17
Source File: QPopup.java    From pumpernickel with MIT License 5 votes vote down vote up
/**
 * Return true if this popup is being used to display a tooltip.
 */
protected boolean isToolTip() {
	for (int a = 0; a < contents.getComponentCount(); a++) {
		Component child = contents.getComponent(a);
		if (!(child instanceof JToolTip))
			return false;
	}
	return contents.getComponentCount() > 0;
}
 
Example #18
Source File: IGCheckBox2.java    From open-ig with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public JToolTip createToolTip() {
	JToolTip tip = new JToolTip();
	tip.setForeground(Color.BLACK);
	tip.setBackground(Color.YELLOW);
	tip.setFont(getFont());
	return tip;
}
 
Example #19
Source File: QPopupFactory.java    From pumpernickel with MIT License 5 votes vote down vote up
@Override
public Popup getPopup(Component owner, Component contents, int x, int y)
		throws IllegalArgumentException {
	Popup p;
	if (contents instanceof JToolTip) {
		JComponent c = (JComponent) contents;
		return getQPopup(owner, null, c, new Point(x, y));
	} else {
		p = delegate.getPopup(owner, contents, x, y);
	}
	return p;
}
 
Example #20
Source File: IOLocationTileList.java    From pumpernickel with MIT License 5 votes vote down vote up
@Override
public Point getToolTipLocation(MouseEvent event) {
	if (event != null) {
		Point p = event.getPoint();
		int index = locationToIndex(p);
		ListCellRenderer r = getCellRenderer();
		Rectangle cellBounds;

		if (index != -1 && (r instanceof BasicTileCellRenderer)
				&& (cellBounds = getCellBounds(index, index)) != null
				&& cellBounds.contains(p.x, p.y)) {
			String text = getToolTipText(event);
			JToolTip tip = new JToolTip();
			tip.setTipText(text);
			Dimension tipSize = tip.getPreferredSize();
			BasicTileCellRenderer btcr = (BasicTileCellRenderer) r;

			int yOffset = cellBounds.height / 2;
			if (btcr.thumbnail.getUI() instanceof ThumbnailLabelUI) {
				ThumbnailLabelUI ui = (ThumbnailLabelUI) btcr.thumbnail
						.getUI();
				yOffset = ui.getTextRect().y;
			}
			return new Point(cellBounds.x + cellBounds.width / 2
					- tipSize.width / 2, cellBounds.y + yOffset);
		}
	}
	return super.getToolTipLocation(event);
}
 
Example #21
Source File: TooltipImageTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void checkSize(JToolTip tip, int width, int height) {
   Dimension d = tip.getPreferredSize();
   Insets insets = tip.getInsets();
   //6 seems to be the extra width being allocated for some reason
   //for a tooltip window.
   if (!((d.width - insets.right - insets.left - 6) == width) &&
       !((d.height - insets.top - insets.bottom) == height)) {
       throw new RuntimeException("Test case fails: Expected width, height is " + width + ", " + height +
               " whereas actual width, height are " + (d.width - insets.right - insets.left - 6) + " " +
               (d.height - insets.top - insets.bottom));
   }
}
 
Example #22
Source File: SpaceLabel.java    From Open-Realms-of-Stars with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JToolTip createToolTip() {
  JToolTip toolTip = super.createToolTip();
  toolTip.setForeground(GuiStatics.COLOR_COOL_SPACE_BLUE);
  toolTip.setBackground(GuiStatics.COLOR_COOL_SPACE_BLUE_DARK);
  toolTip.setBorder(BorderFactory
      .createLineBorder(GuiStatics.COLOR_COOL_SPACE_BLUE_DARKER));
  return toolTip;
}
 
Example #23
Source File: XLabel.java    From scelight with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a tool tip with the label's font.
 */
@Override
public JToolTip createToolTip() {
	final JToolTip tt = super.createToolTip();
	
	tt.setFont( getFont() );
	
	return tt;
}
 
Example #24
Source File: MultiPageComp.java    From scelight with Apache License 2.0 5 votes vote down vote up
/**
 * Create a tool tip with the same font that is used in the tree.
 */
@Override
public JToolTip createToolTip() {
 final JToolTip tt = super.createToolTip();
 tt.setFont( getFont().deriveFont(
         (float) LEnv.LAUNCHER_SETTINGS.get( LSettings.PAGE_LIST_FONT_SIZE ) ) );
 return tt;
}
 
Example #25
Source File: CfgPropsDocAndTooltipQuery.java    From nb-springboot with Apache License 2.0 5 votes vote down vote up
@Override
protected void query(CompletionResultSet completionResultSet, Document document, int caretOffset) {
    final StyledDocument styDoc = (StyledDocument) document;
    Element lineElement = styDoc.getParagraphElement(caretOffset);
    int lineStartOffset = lineElement.getStartOffset();
    int lineEndOffset = lineElement.getEndOffset();
    try {
        String line = styDoc.getText(lineStartOffset, lineEndOffset - lineStartOffset);
        if (line.endsWith("\n")) {
            line = line.substring(0, line.length() - 1);
        }
        if (showTooltip) {
            logger.log(FINER, "Tooltip on: {0}", line);
        } else {
            logger.log(FINER, "Documentation on: {0}", line);
        }
        if (!line.contains("#")) {
            //property name extraction from line
            Matcher matcher = PATTERN_PROP_NAME.matcher(line);
            if (matcher.matches()) {
                String propPrefix = matcher.group(1);
                ConfigurationMetadataProperty propMeta = sbs.getPropertyMetadata(propPrefix);
                if (propMeta != null) {
                    if (showTooltip) {
                        final JToolTip toolTip = new JToolTip();
                        toolTip.setTipText(Utils.shortenJavaType(propMeta.getType()));
                        completionResultSet.setToolTip(toolTip);
                    } else {
                        completionResultSet.setDocumentation(new CfgPropCompletionDocumentation(propMeta));
                    }
                }
            }
        }
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
    completionResultSet.finish();
}
 
Example #26
Source File: SeaGlassToolTipUI.java    From seaglass with Apache License 2.0 5 votes vote down vote up
private int getComponentState(JComponent c) {
    JComponent comp = ((JToolTip) c).getComponent();

    if (comp != null && !comp.isEnabled()) {
        return DISABLED;
    }
    return SeaGlassLookAndFeel.getComponentState(c);
}
 
Example #27
Source File: JComponentOperator.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public JToolTip waitToolTip() {
    return ((JToolTip) waitComponent(WindowOperator.
            waitWindow(new JToolTipWindowFinder(),
                    0,
                    getTimeouts(),
                    getOutput()),
            new JToolTipFinder(),
            0,
            getTimeouts(),
            getOutput()));
}
 
Example #28
Source File: JComponentOperator.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Showes tool tip.
 *
 * @return JToolTip component.
 * @throws TimeoutExpiredException
 */
public JToolTip showToolTip() {
    enterMouse();
    moveMouse(getCenterXForClick(),
            getCenterYForClick());
    return waitToolTip();
}
 
Example #29
Source File: FreeColToolTipUI.java    From freecol with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Dimension getPreferredSize(JComponent c) {
    String tipText = ((JToolTip)c).getTipText();
    if (tipText == null || tipText.isEmpty()) {
        return new Dimension(0, 0);
    }

    float x = 0f;
    float y = 0f;
    for (String line : lineBreak.split(tipText)) {
        if (line.isEmpty()) {
            y += LEADING;
            continue;
        }
        AttributedCharacterIterator styledText
            = new AttributedString(line).getIterator();
        LineBreakMeasurer measurer = new LineBreakMeasurer(styledText, frc);

        while (measurer.getPosition() < styledText.getEndIndex()) {

            TextLayout layout = measurer.nextLayout(maximumWidth);

            x = Math.max(x, layout.getVisibleAdvance());
            y += layout.getAscent() + layout.getDescent() + layout.getLeading();

        }
    }
    return new Dimension((int) (x + 2 * margin),
                         (int) (y + 2 * margin));

}
 
Example #30
Source File: FreeColToolTipUI.java    From freecol with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void paint(Graphics g, JComponent c) {
    if (c.isOpaque()) {
        ImageLibrary.drawTiledImage("image.background.FreeColToolTip",
                                    g, c, null);
    }

    g.setColor(Color.BLACK); // FIXME: find out why this is necessary

    Graphics2D graphics = (Graphics2D)g;
    float x = margin;
    float y = margin;
    for (String line : lineBreak.split(((JToolTip) c).getTipText())) {
        if (line.isEmpty()) {
            y += LEADING;
            continue;
        }
        AttributedCharacterIterator styledText =
            new AttributedString(line).getIterator();

        LineBreakMeasurer measurer = new LineBreakMeasurer(styledText, frc);

        while (measurer.getPosition() < styledText.getEndIndex()) {

            TextLayout layout = measurer.nextLayout(maximumWidth);

            y += (layout.getAscent());
            float dx = layout.isLeftToRight() ?
                0 : (maximumWidth - layout.getAdvance());

            layout.draw(graphics, x + dx, y);
            y += layout.getDescent() + layout.getLeading();
        }
    }
 }