0

I created a program that using the Robot class to output some text on my notepad.

public class Main extends Thread implements KeyListener {

  public Main() {
     addKeyListener(this);
     ...
  }

I would like to stop it by clicking on a certain key, is it possible? I tried to implement it and add it but it's a compilation error.

My class is a sub-class of Thread.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
Imri Persiado
  • 1,857
  • 8
  • 29
  • 45
  • 1
    "*I tried to implement it and add it but it's a compilation error.*" => in that case, showing your code would certainly help... – assylias Feb 12 '13 at 19:25
  • public class Main extends Thread implements KeyListener .... on the constructor I tried: addKeyListener(this) which is a compilation error – Imri Persiado Feb 12 '13 at 19:26
  • 1
    please edit your question and add the Codes in it. – Saju Feb 12 '13 at 19:30

1 Answers1

0

public class Main extends Thread implements KeyListener {

If you look at the javadoc for the Thread class, you will see that it doesn't contain the addKeyListener method, hence the compilation error.

Note, however, when using java.awt.Robot you are concerned about issuing KeyEvents rather than listening for them:

Robot robot = new Robot(); 
 // Create a delay of 5 sec so that you can open notepad 
robot.delay(5000);
robot.keyPress(...); 

Edit: To exit, you could emulate the key combination ALT+F4.

robot.keyPress(KeyEvent.VK_ALT);  
robot.keyPress(KeyEvent.VK_F4);  
robot.keyRelease(KeyEvent.VK_ALT);  
robot.keyRelease(KeyEvent.VK_F4);

Note the key release commands. This is necessary to disengage the key state from the previous key combination.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • I will accept your answer when it will be possible, in the mean time do you have an idea how I can implement it?setting some kind of a listener? I mean I'm looking for a way to shut down the program by the keyboard – Imri Persiado Feb 12 '13 at 19:32