简体   繁体   中英

Java Netbeans - Key Listener doesn't work

After searching on internet why it's happening and trying to change my code in any possible way that I know, it still doesn't work. Basiclly i want to make my JFrame appear when shift is hold. That's my code:

public DesktopMenu() {
    initComponents();
    setFocusable(true);

    //Listening to the mouse movement to change position of the window
    this.addMouseMotionListener(new MouseAdapter(){
        @Override
        public void mouseMoved(MouseEvent e){
            xPos = e.getX();
            yPos = e.getY();
            setLocation((e.getXOnScreen()-xPos),(e.getYOnScreen()-yPos));
        }
    });
    //This should listen to the key, when it's pressed window just appear.
    this.addKeyListener(new KeyListener(){
        @Override
        public void keyPressed(KeyEvent e){
            if(e.getKeyCode() == KeyEvent.VK_SHIFT){
                setVisible(true);
            }else{
                setVisible(false);
            }
        };
        @Override
        public void keyReleased(KeyEvent e) {
        }

        @Override
        public void keyTyped(KeyEvent e) {
        }
    });
}

I run the window in standard Java Class with new DesktopMenu().setVisible(false); 'cause i want to make it just appear when SHIFT is pressed and hold. Thanks in advance.

If you've searched KeyListeners, you'll find that one of the most common problems (other than that they usually should be avoided with Swing applications) is that they won't work if the component that is listened to doesn't have focus. Well the problem you're having is similar but on a bigger scale: the KeyListener won't work if the application listened to doesn't have focus and isn't even visible.

In short, what you are trying to do cannot be done in core Java. Consider using another utility that can do this for you, such as AutoIt if you are running in a Windows environment.


It all depends on the details of what you're trying to do, what environment, and so on. But AutoIt can listen to global keypresses. You can tie it into your Java app by one of several ways, but the easiest is to simply send messages to each other via the standard input and output sockets. And then when AutoIt detects the correct keypress, it sends a message to the Java via ConsoleWrite(...) , and the Java app responds by reading it in via, say a Scanner.

I do know that I would never use the shift key as the hotkey since that will make the user's computer completely non-functionable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM