Tooltip text changing depending on which words are

2019-08-30 01:18发布

问题:

Is it possible to make it so that the tooltip displayed will change when over certain keywords inside of some swing object? The content will be completely defined by the code so I could use text positioning if that would help. Thanks

Edit:

Okay, specifically what I would be doing is creating a custom display box for text to use as a combat log. This will be overtop my animations, a hud if you will. What I am thinking, is that I can use a tooltip to display the attributes behind combat calculations, while de-cluttering the log for people who know how things work already.

回答1:

Override getToolTipText(...). Simple example:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.*;
import javax.swing.plaf.*;
import javax.swing.UIManager.*;


public class ToolTipPanel extends JPanel
{
    public ToolTipPanel()
    {
        setPreferredSize( new Dimension(200, 200) );
        setToolTipText("");
    }

    public void paintComponent(Graphics g)
    {
        g.setColor( Color.red );
        g.fillRect(0, 0, 100, 200);
        g.setColor( Color.blue );
        g.fillRect(100, 0, 100, 200);
    }

    public String getToolTipText(MouseEvent e)
    {
        if (e.getX() < 100)
            return "red";
        else
            return "blue";
    }

    public Point getToolTipLocation(MouseEvent e)
    {
        Point p = e.getPoint();
        p.y += 15;
        return p;

    }

    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.getContentPane().add( new ToolTipPanel() );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }
}

With a text component you would need to use the mouse point and the getViewToModel() method to get the text from the Document.