Re: Tooltip location outside of JComponenet
Albert <albert@voila.fr> wrote:
Le 17/11/2009 13:41, Christian Kaufhold a ??crit :
Albert<albert@voila.fr> wrote:
Hi, i have a JTable in a JScrollPane, and on some circonstance, when
scrolling, the tooltip is moved above the jtable and even its headers.
So do you know how to prevent this ? I 'd like the tooltip to stay in
the area of the jtable.
Override JTable.getToolTipLocation
Thanks but it doesn't really work. I've used this code:
public Point getToolTipLocation(MouseEvent event) {
Point location= MouseInfo.getPointerInfo().getLocation();
SwingUtilities.convertPointFromScreen(location, this);
return location;
}
Eh, why not just use event.getPoint()?
But:
1/ By default swing put the tooltip a little bit below the cursor, so
some calculations are missing in my code
The default ToolTipManager calculation just adds 20 pixels to y.
2/ When the value returned by this method change the tooltip is hidden
and re-shown so with my code the tooltip follow the mouse at each
mouseMoved...
Only return non-null if you want the tooltip moved.
(You also have to return non-null *always* if the tool tip *text* changes,
otherwise the default location will be chosen again.)
Try something like this:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class TableToolTip
{
public static void main(String[] args)
{
JTable t = new JTable(20, 8)
{
private JToolTip toolTip; // active tooltip (TODO: leaks)
private JToolTip nextToolTip; // just to avoid double creation
private int toolTipRow = -1, toolTipColumn = -1;
public JToolTip createToolTip()
{
if (nextToolTip != null)
{
toolTip = nextToolTip;
nextToolTip = null;
}
else
toolTip = super.createToolTip();
return toolTip;
}
public String getToolTipText(MouseEvent e)
{
Point p = e.getPoint();
int row = rowAtPoint(p);
int column = columnAtPoint(p);
return row+" "+column;
}
public Point getToolTipLocation(MouseEvent e)
{
Point p = e.getPoint();
int row = rowAtPoint(p);
int column = columnAtPoint(p);
if (toolTip == null || !toolTip.isShowing() || row != toolTipRow || column != toolTipColumn)
{
toolTipRow = row;
toolTipColumn = column;
nextToolTip = super.createToolTip();
nextToolTip.setTipText(getToolTipText(e));
Dimension d = nextToolTip.getPreferredSize();
Point result = new Point(p);
result.y += 20; // default in ToolTipManager
// Do not allow outside below
if (result.y + d.height > getHeight())
{
result.y = getHeight() - d.height;
// Put above if no space below cursor
if (result.y < p.y + 20)
result.y = Math.min(p.y - d.height - 20, result.y);
}
return result;
}
return null;
}
};
JFrame f = new JFrame();
f.getContentPane().add(new JScrollPane(t));
f.setBounds(200, 200, 400, 400);
f.setVisible(true);
}
}