如何在后台运行此keylistener?我应该在代码部分中嵌入什么?当我切换到另一个窗口时,代码在前窗口中工作正常
失去它的功能

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();
        }
    }

最佳答案

您可以使用JNativeHook Java库,即使您不在窗口中,该库也将获取键,这是JNativehook附带的示例代码。从我的较旧的项目之一中提取。如果没有清除,请随时提出问题,您将需要下载JNativeHook jar文件

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) {
    }
}

10-05 22:47