Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to run this key listener in background in java

Tags:

java

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();
    }
}
like image 432
rajat kumar Avatar asked Sep 18 '25 16:09

rajat kumar


2 Answers

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) {
    }
}
like image 75
Adeel Ahmed Avatar answered Sep 20 '25 06:09

Adeel Ahmed


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

like image 30
ControlAltDel Avatar answered Sep 20 '25 07:09

ControlAltDel