简体   繁体   中英

keylistener in java not working

I want my java program to be running in the background by default, but use a keylistener to call my changewallpaper class. The changewallpaper class definently works, but the keylistener does not call the method. The keyevent will be changed later it's currently just for testing.

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class listener implements KeyListener {

    public static void main(String[] args){

    }


    @Override
    public void keyReleased(KeyEvent arg0) {
        int key = arg0.getKeyCode();

        if (key == KeyEvent.VK_UP) {
                changewallpaper.main();
        }
    }

    @Override
    public void keyTyped(KeyEvent arg0) {
        int key = arg0.getKeyCode();

        if (key == KeyEvent.VK_UP) {
                changewallpaper.main();
        }
    }


    @Override
    public void keyPressed(KeyEvent arg0) {
        int key = arg0.getKeyCode();

        if (key == KeyEvent.VK_UP) {
                changewallpaper.main();
        }
    }
}

A KeyListener does not listen to all keyboard events indiscriminately - it only listens to events on a particular Component, when that Component has keyboard focus. You have to attach the listener to something with an addKeyListener method or similar.

See the Java How to Write a Key Listener tutorial

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