この Web ページhttp://code.google.com/p/jnativehook/wiki/examples (以下に掲載)の最後の例を見ています。
具体的にはnativeKeyReleased(NativeKeyEvent e)
方法。これに遭遇したのは、swing を使用するアプリケーションでネイティブフックが適切に初期化されないことがあったためです。メソッドで適切に閉じていなかったので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();
}
});
}
}