我正在查看此网页http://code.google.com/p/jnativehook/wiki/examples上的最后一个示例(发布在下面)
具体nativeKeyReleased(NativeKeyEvent e)
方法。我偶然发现了这一点,因为我有时在使用 swing 的应用程序中使用 nativehook 无法正确初始化;因为我没有在windowClosed()
方法中正确关闭它..
为什么需要使用Runnable
in nativeKeyReleased(NativeKeyEvent e)
?
逐字:
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();
}
});
}
}