0

Let's say that I have window which is not focused. Is there any other way of catching pressed keys that using KeyListener.

import javax.swing.JFrame;

public class Main {

    public static void main(String[] args) {
        Window w = new Window();
    }    
}

class Window extends JFrame {
    private static final long serialVersionUID = -6791503228233798055L;
    public JFrame fr;

    Window() {
        fr = new JFrame();
        fr.setVisible(true);
        fr.setSize(500, 500);
        fr.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
}

How to catch keys without focused window and KeyListener?

Cœur
  • 37,241
  • 25
  • 195
  • 267
magic-sudo
  • 1,206
  • 9
  • 15
  • 1
    [Key Bindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) might be what you're looking for. Although this does require some kind of focus, you can require the focus for any element to be `WHEN_IN_FOCUS_WINDOW`, rather than requiring that specific component to have focus. ***If you want to catch key events without any GUI elements being in focus or without GUI entirely**, youll need to use a [native listener](http://code.google.com/p/jnativehook/)* – Vince Jan 31 '15 at 17:52
  • Thank you @VinceEmigh but I will rather use C++ . – magic-sudo Jan 31 '15 at 18:03
  • 1
    Native listeners use C++ (or another language native to the platform, such as C or assembly) under the hood. It's accessing native details using something called the Java Native Interface (JNI). You could achieve the same by writing your own implementation using JNI, but why waste time re-inventing the wheel? – Vince Jan 31 '15 at 18:05

1 Answers1

-2

KeyListener is just an interface - it doesn't do anything.

You need somebody to tell you that the event occured. Usually you pass yourself as somebody that want to know about events to some window or pane. JVM doesn't allow to do register in this way to operating system itself. You will probably need external library to do so.

Here you have very similar topic.

Community
  • 1
  • 1
damienix
  • 6,463
  • 1
  • 23
  • 30
  • 2
    There are a ton of native listeners available which make this kind of thing extremely easy. This question is also asking about different ways to catch key events, not "how can we catch key events without a window *and why wouldnt we be able to*" – Vince Jan 31 '15 at 17:57
  • Updated according to your suggestion to use external library. – damienix Jan 31 '15 at 18:01