下面列出了怎么用javax.swing.JToolTip的API类实例代码及写法,或者点击链接到github查看源代码。
@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 );
}
/**
* 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);
}
@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 );
}
/**
* 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();
}
/**
* @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);
}
}
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);
}
@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();
}
}
/**
* @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;
}
@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);
}
}
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() + '}';
}
};
}
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);
}
});
}
/**
* 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);
}
}
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);
}
}
/**
* 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));
}
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.");
}
@Override
public JToolTip createToolTip() {
JToolTip ret = super.createToolTip();
if (toolTipOverrideFont != null) {
ret.setFont(toolTipOverrideFont);
}
return ret;
}
@Override
public void installUI( JComponent c ) {
super.installUI( c );
// update HTML renderer if necessary
FlatLabelUI.updateHTMLRenderer( c, ((JToolTip)c).getTipText(), false );
}
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));
}
}
protected JComponent createTooltipComponent(String content) {
if (!isValidTooltipContent(content)) {
return null;
}
JToolTip tt = new JToolTip();
tt.setTipText(content);
return tt;
}
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));
}
}
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));
}
}
@Override
public JToolTip createToolTip() {
if (component instanceof JComponent) {
return ((JComponent) component).createToolTip();
} else {
return super.createToolTip();
}
}
@Override
public Point getToolTipLocation( MouseEvent event ) {
JToolTip tip = createToolTip();
tip.setTipText( getToolTipText() );
Dimension d = tip.getPreferredSize();
Point retValue = new Point( getWidth()-d.width, -d.height );
return retValue;
}
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));
}
protected ProfilerXYChart createChart(SynchronousXYItemsModel itemsModel,
PaintersModel paintersModel,
final boolean smallPanel) {
ProfilerXYChart chart;
if (smallPanel) {
chart = new ProfilerXYChart(itemsModel, paintersModel) {
public JToolTip createToolTip() {
lastTooltip = new SmallTooltip(this);
return lastTooltip;
}
public Point getToolTipLocation(MouseEvent e) {
return getSmallTooltipLocation(e, smallTooltipManager);
}
};
smallTooltipManager = new SmallTooltipManager(chart);
chart.setToolTipText(NO_DATA_TOOLTIP); // Needed to enable the tooltip
ToolTipManager.sharedInstance().registerComponent(chart);
} else {
chart = new ProfilerXYChart(itemsModel, paintersModel);
}
chart.addPreDecorator(new XYBackground());
chart.setFitsWidth(false);
chart.getSelectionModel().setHoverMode(ChartSelectionModel.HOVER_EACH_NEAREST);
return chart;
}
@Override
public Object getValueAt(Object node, String columnID)
throws UnknownTypeException
{
if(node instanceof JToolTip) {
return getTooltip( ( (JToolTip) node), columnID);
}
switch (columnID) {
case Constants.WATCH_TYPE_COLUMN_ID:
if(node instanceof ModelNode) {
return ((ModelNode)node).getType();
}
break;
case Constants.WATCH_VALUE_COLUMN_ID:
if(node instanceof ModelNode) {
Object value;
try {
value = ((ModelNode)node).getValue();
}
catch (UnsufficientValueException e) {
/*
* This should not happened for property in eval command
* becuase we are not able to send command property_value.
*/
return VariablesModel.NULL;
}
return value == null ? VariablesModel.NULL : value;
}
break;
}
throw new UnknownTypeException(node);
}
@Override
public Dimension getPreferredSize(JComponent c) {
FontMetrics fm = c.getFontMetrics(c.getFont());
Insets insets = c.getInsets();
Dimension prefSize = new Dimension(insets.left+insets.right,
insets.top+insets.bottom);
String text = ((JToolTip)c).getTipText();
if (text != null && !text.isEmpty()) {
prefSize.width += fm.stringWidth(text);
prefSize.height += fm.getHeight();
}
return prefSize;
}
private String getTooltip(JToolTip tooltip, String columnId) throws UnknownTypeException {
Object row = tooltip.getClientProperty(VariablesModel.GET_SHORT_DESCRIPTION);
// TODO
if (row instanceof ModelNode) {
return getValueAt(row, columnId).toString();
}
throw new UnknownTypeException(tooltip);
}
@Override
public Point getToolTipLocation(MouseEvent event) {
JToolTip tip = createToolTip();
tip.setTipText(getToolTipText());
Dimension d = tip.getPreferredSize();
Point retValue = new Point(getWidth() - d.width, -d.height);
return retValue;
}
@Override
public JToolTip createToolTip() {
JToolTip tooltp = new JToolTip();
tooltp.setBackground(SystemColor.control);
tooltp.setFont(getFont());
tooltp.setOpaque(true);
tooltp.setComponent(this);
tooltp.setBorder(null);
return tooltp;
}