0

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();
        }
    }
}
jerhynsoen
  • 205
  • 1
  • 7
  • 20
  • Do you have `something.add(my_listener)` anywhere in your code? – Jon Egeland Jul 06 '12 at 23:16
  • nope, didn't see anything like that in the example from oracle.. i dont think. http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/events/KeyEventDemoProject/src/events/KeyEventDemo.java – jerhynsoen Jul 06 '12 at 23:19
  • @jerhynsoen Look again. `addKeyListener` – TheZ Jul 06 '12 at 23:21

1 Answers1

1

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

DNA
  • 42,007
  • 12
  • 107
  • 146
  • so i can't just tell it to listen for a key anytime or anywhere? like if I am using another program for example? – jerhynsoen Jul 06 '12 at 23:21
  • No, I'm afraid not - you can listen within your application though (see http://stackoverflow.com/questions/1714349/global-keylogger-in-java). The only way round this is to use native code hooked into Java through JNI. – DNA Jul 06 '12 at 23:21