Reputation: 199
I have a stackPane
, filled with a Circle and a couple of lines.
I want to display a tooltip while hovering over the StackPane and the tooltip should contain the X/Y coords
of the mouse.
I know how to get the Coords of the mouse, but I'm unable to find a way of showing the tool tip.
Can any of ou guys help me with that?..
Upvotes: 4
Views: 14440
Reputation: 580
The prior solution is OK, but it gets called for every mouse movement.
Instead, here's a solution that just gets called once when it's about to display the tooltip:
The JavaFx 8 Tooltip provides event callbacks just before and after the tooltip displays (and just before and after it's taken down). So, install an event handler for the "just before" call like this below. The window event doesn't give you the current mouse coordinates, unfortunately, but you can still get them at any time with java.awt.MouseInfo.getPointerInfo().getLocation() as below.
Tooltip t = new Tooltip();
Tooltip.install(yournode, t);
t.setOnShowing(ev -> {// called just prior to being shown
Point mouse = java.awt.MouseInfo.getPointerInfo().getLocation();
Point2D local = yournode.screenToLocal(mouse.x, mouse.y);
// my app-specific code to get the chart's yaxis value
// then set the text as I want
double pitch = yaxis.getValueForDisplay(local.getY()).doubleValue();
double freq = AudioUtil.pitch2frequency(pitch);
t.setText(String.format("Pitch %.1f: %.1f Hz %.1f samples", pitch, freq, audio.rate / freq));
});
Works for me.
Upvotes: -1
Reputation: 64
I solved it like this:
Tooltip mousePositionToolTip = new Tooltip("");
gridPane.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
String msg = "(x: " + event.getX() + ", y: " + event.getY() + ")\n(sceneX: "
+ event.getSceneX() + ", sceneY: " + event.getSceneY() + ")\n(screenX: "
+ event.getScreenX() + ", screenY: " + event.getScreenY() + ")";
mousePositionToolTip.setText(msg);
Node node = (Node) event.getSource();
mousePositionToolTip.show(node, event.getScreenX() + 50, event.getScreenY());
}
});
It will show a ToolTip in right of your mouse-pointer. You can replace your StackPane with gridPane in my code and it should work. But i didn't test it.
Upvotes: 3
Reputation: 151
Anshul Parashar's answer probably works, but ToolTip also has a 'installation' static helper method to handle display on hover.
Assuming n is a Node:
Tooltip tp = new Tooltip("at stack tool");
Tooltip.install(n, tp);
Upvotes: 14
Reputation: 3126
try this...
Tooltip tp = new Tooltip("at stack tool");
stackpane.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent t) {
Node node =(Node)t.getSource();
tp.show(node, FxApp.stage.getX()+t.getSceneX(), FxApp.stage.getY()+t.getSceneY());
}
});
Upvotes: 4