如何根据鼠标位置显示工具提示? - JavaFX

时间:2014-01-16 10:30:07

标签: user-interface user-controls javafx tooltip

我有一个stackPane,里面有一个圆圈和几行。

我希望在将鼠标悬停在StackPane上时显示工具提示,并且工具提示应包含鼠标的X/Y coords

我知道如何获得鼠标的Coords,但我无法找到显示工具提示的方法。

你们中的任何人都可以帮助我吗?..

4 个答案:

答案 0 :(得分:11)

Anshul Parashar的答案可能有效,但ToolTip还有一个“安装”静态助手方法来处理悬停时的显示。

假设n是节点:

Tooltip tp = new Tooltip("at stack tool");
Tooltip.install(n, tp);

答案 1 :(得分:4)

试试这个......

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());
        }
    });

答案 2 :(得分:3)

我这样解决了:

    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());
        }

    });

它会在鼠标指针右侧显示一个工具提示。您可以在我的代码中用gridPane替换StackPane,它应该可以工作。但我没有测试它。

答案 3 :(得分:-1)

先前的解决方案没问题,但每次鼠标移动都会调用它。

相反,这是一个解决方案,当它即将显示工具提示时,它会被调用一次:

JavaFx 8工具提示在工具提示显示之前和之后(以及之前和之后)提供事件回调。因此,在&#34;之前安装一个事件处理程序。如下所示。不幸的是,窗口事件并没有为您提供当前鼠标坐标,但您仍然可以随时使用java.awt.MouseInfo.getPointerInfo()。getLocation()获取它们,如下所示。

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));
});

适合我。