javafx 8 - 计算按下的点击次数和键数

时间:2016-02-09 13:14:54

标签: java javafx-8

我正在开发像时间跟踪器,我需要计算在特定时间范围内使用鼠标或键盘的次数。我不是指点击界面,而是点击和共同的关键事件。我怎么能拦截它?

1 个答案:

答案 0 :(得分:0)

我终于找到了解决方案:

首先我们需要创建监听器类

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void txtUserName_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (txtUserName.Text.Length > 0)
            tbUsername.Visibility = Visibility.Collapsed;
        else
            tbUsername.Visibility = Visibility.Visible;
    }

    private void pwbPassword_PasswordChanged(object sender, RoutedEventArgs e)
    {
        if (pwbPassword.Password.Length > 0)
            tbPassword.Visibility = Visibility.Collapsed;
        else
            tbPassword.Visibility = Visibility.Visible;
    }
}

然后,在您的代码中执行以下操作:

import org.jnativehook.mouse.NativeMouseEvent;
import org.jnativehook.mouse.NativeMouseInputListener;

public class NativeMouseListener implements NativeMouseInputListener {
    public void nativeMouseClicked(NativeMouseEvent e) {
        System.out.println("Mosue Clicked: " + e.getClickCount());
    }

    public void nativeMousePressed(NativeMouseEvent e) {
        //System.out.println("Mosue Pressed: " + e.getButton());
    }

    public void nativeMouseReleased(NativeMouseEvent e) {
        //System.out.println("Mosue Released: " + e.getButton());
    }

    public void nativeMouseMoved(NativeMouseEvent e) {
        //System.out.println("Mosue Moved: " + e.getX() + ", " + e.getY());
    }

    public void nativeMouseDragged(NativeMouseEvent e) {
        //System.out.println("Mosue Dragged: " + e.getX() + ", " + e.getY());
    }
}

你可以从那里拿到jnative jar:

try {
    GlobalScreen.registerNativeHook();
}
catch (NativeHookException ex) {
    System.err.println("There was a problem registering the native hook.");
    System.err.println(ex.getMessage());
    System.exit(1);
}

GlobalScreen.addNativeMouseListener(new NativeMouseListener());

但我不确定它是否适用于mac。稍后再试。希望有所帮助