工具提示:如何获取触发提示的鼠标坐标?

Tooltip: how to get mouse coordinates that triggered the tip?

要求:将触发工具提示的鼠标事件的坐标显示为文本。对于 contextMenu,位置存储在 contextMenuEvent 中,因此我会听取 contextMenuRequested 并根据需要进行更新。

找不到类似的工具提示,所以玩了一下(见下面的例子):

有什么想法吗?

public class DynamicTooltipMouseLocation extends Application {

    protected Button createButton(AnchorLocation location) {
        Tooltip t = new Tooltip("");
        String text = location != null ? location.toString() 
                : t.getAnchorLocation().toString() + " (default)";
        if (location != null) {
            t.setAnchorLocation(location);
        }
        t.setOnShown(e -> {
            // here we get a stable tooltip
            t.textProperty().set("x/y: " + t.getX() + "/" + t.getY() + "\n" +
                    "ax/y: " + t.getAnchorX() + "/" + t.getAnchorY());
        });
        Button button = new Button(text);
        button.setTooltip(t);
        button.setOnContextMenuRequested(e -> {
            LOG.info("context: " + text + "\n      " +
                    "scene/screen/source " + e.getSceneX() + " / " + e.getScreenX() + " / " + e.getX());
        });
        button.setOnMouseMoved(e -> {
            LOG.info("moved: " + text + "\n      " +
            "scene/screen/source " + e.getSceneX() + " / " + e.getScreenX() + " / " + e.getX());
        });
        return button;
    }

    @Override
    public void start(Stage stage) throws Exception {
        VBox pane = new VBox(createButton(AnchorLocation.CONTENT_TOP_LEFT));
        Scene scene = new Scene(pane);
        stage.setScene(scene);
        stage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }

    @SuppressWarnings("unused")
    private static final Logger LOG = Logger
            .getLogger(DynamicTooltipMouseLocation.class.getName());
}

我不确定我是否理解了你的问题,但如果你正在寻找鼠标的屏幕坐标,就在工具提示显示的位置,我想你差不多明白了。

您已经看过 Tooltip class 及其内部 class TooltipBehavior

对于初学者来说,有这些硬编码的偏移量:

private static int TOOLTIP_XOFFSET = 10;
private static int TOOLTIP_YOFFSET = 7;

然后,在内部 class 节点中添加鼠标移动处理程序,在屏幕坐标中跟踪鼠标,并显示基于多个计时器的工具提示:

    t.show(owner, event.getScreenX()+TOOLTIP_XOFFSET,
                            event.getScreenY()+TOOLTIP_YOFFSET);

鉴于它使用此 show 方法:

public void show(Window ownerWindow, double anchorX, double anchorY)

您要找的坐标就是这些:

coordMouseX=t.getAnchorX()-TOOLTIP_XOFFSET;
coordMouseY=t.getAnchorY()-TOOLTIP_YOFFSET;

无论工具提示锚点位置如何设置。

我也在你对 的回答中检查了这一点,这些值与你设置为工具提示的 Point2D screen 相同。

无论如何,由于此解决方案使用来自私有 API 的硬编码字段,我假设您不会喜欢它,因为这些可能会在不通知的情况下更改...