How to get location of mouse in JavaFX?

后端 未结 3 981
难免孤独
难免孤独 2020-12-05 16:13

I am a beginner in java(fx).
How do you get the mouse location in x and y in JavaFX? I tried using AWT\'s MouseInfo(also imported it), but it\'s not worki

3条回答
  •  抹茶落季
    2020-12-05 16:46

    JavaFx 8 WindowEvent doesn't provide the (x,y) location of the mouse, unfortunately. I solved this (and it works fine) by using the AWT MouseInfo like this:

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

提交回复
热议问题