3

How to run this key listener in background? What should I embed in code section? Code is working fine in front window but when I switch to another window it loses its functionality.

import java.util.*;
import javax.imageio.*;
import java.awt.*;
import javax.swing.*; 

public class KeyListenerExample extends Frame implements KeyListener {
    Label l;  
    TextArea area;  

    KeyListenerExample() {
        l=new Label();  
        l.setBounds(20,50,100,20);  
        area=new TextArea();  
        area.setBounds(20,80,300, 300);  
        area.addKeyListener(this);

        add(l);add(area);  
        setSize(400,400);  
        setLayout(null);  
        setVisible(true); 
    }

    public void keyPressed(KeyEvent e) {
        l.setText("Key Pressed");
    }

    public void keyReleased(KeyEvent e) {
        l.setText("Key Released");
    }

    public void keyTyped(KeyEvent e) {
        l.setText("Key Typed");
    }

    public static void main(String[] args) {
        new KeyListenerExample();
    }
}
Abra
  • 19,142
  • 7
  • 29
  • 41
rajat kumar
  • 35
  • 1
  • 10
  • Are you saying you want your app to continue to capture key presses even when your application is not the focused app? – Gregg Jun 12 '17 at 14:58
  • 1
    If the Frame is in the background, it won't receive keypresses. – Steve Smith Jun 12 '17 at 14:58
  • 1
    Possible duplicate of [Java key listener to track all keystrokes](https://stackoverflow.com/questions/12177416/java-key-listener-to-track-all-keystrokes) – Gregg Jun 12 '17 at 14:59

2 Answers2

1

If this other window is also running in the same java process as the first window, you can use

KeyboardFocusManager.addKeyEventDispatcher(java.awt.KeyEventDispatcher)

With your custom KeyEvenDispatcher

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
1

you can use JNativeHook java library that will grab the keys even if you are not in your window, here is the sample code attached for JNativehook. from one of my older projects.feel free to ask questions if it doesnt clears,you will be needing to download JNativeHook jar file

import java.awt.EventQueue;
import java.awt.Toolkit;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JFrame;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

public class Main2 extends JDialog implements NativeKeyListener {

    private static final long serialVersionUID = 1L;

    public static void main(String[] args) throws Exception {

        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {

                    Main2 frame = new Main2(new JFrame() {
                        @Override
                        public boolean isShowing() {
                            return true;
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     * 
     * @throws IOException
     */
    public Main2(JFrame jFrame) throws IOException, NativeHookException {
        System.setProperty("sun.java2d.noddraw", "true");
        setBounds(0, 0, 1, 1);

        setUndecorated(true);
        this.setLocationRelativeTo(null);

        try {
            SwingExecutorService ses = new SwingExecutorService();
            GlobalScreen.getInstance().setEventDispatcher(ses);
            GlobalScreen.registerNativeHook();
            Logger loggy = Logger.getLogger(GlobalScreen.class.getPackage().getName());
            loggy.setLevel(Level.SEVERE);
        } catch (Exception e) {

        }

        GlobalScreen.getInstance().addNativeKeyListener(this);

        setFocusable(true);
        setVisible(true);

    }

    @Override
    public void nativeKeyPressed(NativeKeyEvent e) {
        char ch = e.getKeyChar();
        System.out.println(e.getKeyText(e.getKeyCode()));
        int key = e.getKeyCode();
        System.out.println(ch);
        System.out.println(key);
        String modifiers = e.getModifiersText(e.getModifiers());
        int rawCode = e.getRawCode();
        System.out.println(rawCode);
    }

    @Override
    public void nativeKeyTyped(NativeKeyEvent e) {
    }

    private class SwingExecutorService extends AbstractExecutorService {
        private EventQueue queue;

        public SwingExecutorService() {
            queue = Toolkit.getDefaultToolkit().getSystemEventQueue();
        }

        @Override
        public void shutdown() {
            queue = null;
        }

        @Override
        public List<Runnable> shutdownNow() {
            return new ArrayList<>(0);
        }

        @Override
        public boolean isShutdown() {
            return queue == null;
        }

        @Override
        public boolean isTerminated() {
            return queue == null;
        }

        @Override
        public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
            return true;
        }

        @Override
        public void execute(Runnable r) {
            EventQueue.invokeLater(r);
        }
    }

    @Override
    public void nativeKeyReleased(NativeKeyEvent arg0) {
    }
}
Adeel Ahmed
  • 413
  • 4
  • 16