kwhat / jnativehook

Global keyboard and mouse listeners for Java.
Other
1.73k stars 344 forks source link

the NativeMouseListener cant get the mouse x,y #401

Open waht-X opened 2 years ago

waht-X commented 2 years ago

my computer is win10. JDK is jdk8(corretto-1.8)

i am using NativeMouseListener to get the x,y. such:

//Point endPoint;
endPoint.x = nativeMouseEvent.getX();

and when i run my process, it throw some error like:

Exception in thread "JNativeHook Dispatch Thread" java.lang.NullPointerException
    at ScreenCapture.JavaHook.GlobalMouseListener.nativeMouseReleased(GlobalMouseListener.java:37)
    at org.jnativehook.GlobalScreen$EventDispatchTask.processButtonEvent(Unknown Source)
    at org.jnativehook.GlobalScreen$EventDispatchTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:750)

but i can use nativeMouseEvent.getPoint to get the coordiantes.

here are my part of code:

package ScreenCapture.JavaHook;

import ScreenCapture.ScreenCapture;
import ScreenCapture.ScreenShot;
import org.jnativehook.mouse.NativeMouseEvent;
import org.jnativehook.mouse.NativeMouseListener;

import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class GlobalMouseListener implements NativeMouseListener {

    private Point startPoint;
    private Point endPoint;

    @Override
    public void nativeMouseClicked(NativeMouseEvent nativeMouseEvent) {

    }

    @Override
    public void nativeMousePressed(NativeMouseEvent nativeMouseEvent) {

        if (GlobalKeyboardListener.mouseStartMoveRecord) {
            System.out.println(nativeMouseEvent.paramString());
            startPoint = nativeMouseEvent.getPoint();
            System.out.println("i am recorded start point");
        }

    }

    @Override
    public void nativeMouseReleased(NativeMouseEvent nativeMouseEvent) {

        if (GlobalKeyboardListener.mouseStartMoveRecord) {
            endPoint.x = nativeMouseEvent.getX();
            endPoint.y = nativeMouseEvent.getY();

            GlobalKeyboardListener.mouseStartMoveRecord = false;

            System.out.println("->already to save photo");
            ScreenShot screenShot = new ScreenShot();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = simpleDateFormat.format(new Date());
            screenShot.saveImage(ScreenCapture.saveFilePath, fileName, startPoint, endPoint);
        }
    }
}
kwhat commented 2 years ago

I don't see anywhere in your class where you initialize endPoint so endPoint is null and endPoint.x is the null pointer exception. Please verify and close if this is the case.