jerhynsoen
jerhynsoen

Reputation: 215

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

Upvotes: 0

Views: 137

Answers (1)

DNA
DNA

Reputation: 42597

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

Upvotes: 1

Related Questions