gpt4 book ai didi

java - JNativeHook 和 swing - 为什么在 nativeKey* 方法中使用 runnable?

转载 作者:行者123 更新时间:2023-12-01 13:53:33 30 4
gpt4 key购买 nike

我正在查看此网页上的最后一个示例 http://code.google.com/p/jnativehook/wiki/examples (发布在下面)

特别是nativeKeyReleased(NativeKeyEvent e)方法。我偶然发现了这一点,因为我在使用 swing 的应用程序中有时无法正确初始化 nativehook;因为我没有在 windowClosed() 方法中正确关闭它..

为什么需要在nativeKeyReleased(NativeKeyEvent e)中使用Runnable

逐字记录:

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

public class SwingExample extends JFrame implements NativeKeyListener, WindowListener {
public SwingExample() {
setTitle("JNativeHook Swing Example");
setSize(300, 150);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
addWindowListener(this);
setVisible(true);
}

public void windowOpened(WindowEvent e) {
//Initialze native hook.
try {
GlobalScreen.registerNativeHook();
}
catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());
ex.printStackTrace();

System.exit(1);
}

GlobalScreen.getInstance().addNativeKeyListener(this);
}

public void windowClosed(WindowEvent e) {
//Clean up the native hook.
GlobalScreen.unregisterNativeHook();
System.runFinalization();
System.exit(0);
}

public void windowClosing(WindowEvent e) { /* Unimplemented */ }
public void windowIconified(WindowEvent e) { /* Unimplemented */ }
public void windowDeiconified(WindowEvent e) { /* Unimplemented */ }
public void windowActivated(WindowEvent e) { /* Unimplemented */ }
public void windowDeactivated(WindowEvent e) { /* Unimplemented */ }

public void nativeKeyReleased(NativeKeyEvent e) {
if (e.getKeyCode() == NativeKeyEvent.VK_SPACE) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, "This will run on Swing's Event Dispatch Thread.");
}
});
}
}

public void nativeKeyPressed(NativeKeyEvent e) { /* Unimplemented */ }
public void nativeKeyTyped(NativeKeyEvent e) { /* Unimplemented */ }

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SwingExample();
}
});
}
}

最佳答案

原因可能有很多。

主要原因是 native 钩子(Hook)可能使用自己的线程来监视输入。由于 Swing 是单线程框架,因此您需要将输出重新同步回该线程(又名事件调度线程)。

您可能还想避免阻塞 native 钩子(Hook)线程,以便它可以继续响应输入

关于java - JNativeHook 和 swing - 为什么在 nativeKey* 方法中使用 runnable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19777179/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com