user1299661
user1299661

Reputation: 193

How do I use the KeyListener interface?

I am just starting to use the KeyListener interface. I want to create a very simple console application. I would like the program to print "hi" if I ever press the key 'ENTER'. Unfortunately, due to my lack of knowledge, when I press the enter/return key on my keyboard, nothing happens. I am not using the Scanner class because it requires the user to type something in and or just hit enter to execute something. I would like a process to continue until it is interrupted by a key press. Here is what my code looks like so far:

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

public class Trash implements KeyListener {
   public void keyPressed(KeyEvent e){
      System.out.println("hi");
      switch (e.getKeyCode()) {
         case KeyEvent.VK_ENTER:
            System.out.println("hi");
      }
   }

   public void keyTyped(KeyEvent e){}

   public void keyReleased(KeyEvent e){}

   public static void main (String [] args){
      Trash obj1 = new Trash();
   }
}

Upvotes: 1

Views: 1709

Answers (1)

JB Nizet
JB Nizet

Reputation: 691775

A KeyListener can only be added to a GUI component. It can't be used in a console application. That's why it's in a java.awt subpackage. AWT = Abstract Window Toolkit, the basic GUI toolkit of Java.

If you want to interrupt a "process" when enter is pressed in the console, you should use a thread for your process, and another thread which reads from standard input and interrupts the other one when something is entered.

Upvotes: 2

Related Questions