3

I have written a program in JAVA language which accepts inputs from console by using Scanner class....

now I want to add this ability to my code to exist a loop (while) when user presses Esc Button. so far I thought Keyboard class can help me but it was just like Scanner...I tried to use events but do not know how to use them correctly....

Source code:

    package switchCase_v1;

     import cs1.Keyboard;
     import java.util.EventObject;
     import java.awt.AWTEvent;
     import java.awt.event.KeyEvent;
     import java.awt.event.ComponentEvent;
     import java.awt.event.InputEvent;
     import java.util.*;

      public class SwithCase {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner(System.in);
        System.out.println("enter the name or number of month: ");
        int monthNumber = input.nextInt();

        while (true) {
            KeyEvent button;
            if (button.getKeyCode() == 27)
                break;
            else if (monthNumber == '\n') {
                System.out.println("enter a number");
                monthNumber = input.nextInt();
            } else {
                switch (monthNumber) {
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                case 6:
                    System.out.println("it has 31 days");
                    monthNumber = input.nextInt();
                    break;
                case 7:
                case 8:
                case 9:
                case 10:
                case 11:
                case 12:
                    System.out.println("it has 30 days");
                    monthNumber = input.nextInt();
                    break;
                default:
                    System.out.println("it is not a valid number");
                    monthNumber = input.nextInt();
                    break;
                }
            }

        }
    }
  }

How I can deal with cases when I want to take into consideration the hitting buttons like "Esc" or "Enter"? I think it should be also applicable by using ASCII codes.

this is the new version of my code:

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner input = new Scanner(System.in);
    System.out.print("Check number of days");
    KeyEvent e;
    if (e.getKeyCode() == KeyEvent.VK_ENTER)
    {
    System.out.println("enter the name or number of month: ");
    int monthNumber=input.nextInt();
    }
    else if (Keyboard.getEventKey()==Keyboard.KEY_ESCAPE)
    {
        System.out.println("GoodBye");
    }
    }   

}

but it has an error saying e object may not have been initialized...!!!!!what should I do?!!!

msc87
  • 943
  • 3
  • 17
  • 39

3 Answers3

8

You're currently making a command-line application which reads stuff from standard input and prints stuff to standard output. How buttons presses are handled depends entirely on the terminal in which your are running your program, and most terminals won't send anything to your application's stdin when escape is pressed.

If you want to catch key events, you'll have to make a GUI application using AWT or Swing. If all you want is to terminate your program while it's running, try pressing Ctrl+C (this works in most terminals).

AardvarkSoup
  • 1,071
  • 8
  • 18
  • TNX a lot...I was reaching what you mentioned after checking all the solutions suggested by other friends...I concluded that it is impossible to add this option to such kind of code without GUIs. – msc87 May 25 '12 at 13:41
  • C# (Mono) is able to implement a cross platform Console.ReadKey() that uses Windows console (when on Windows) and TermInfo console (when on non-Windows). Here's source code: https://github.com/mono/mono/blob/a31c107f59298053e4ff17fd09b2fa617b75c1ba/mcs/class/corlib/System/ConsoleDriver.cs – KFL Apr 20 '14 at 05:32
  • This explanation makes sense - the console implementation intercepts those keystrokes and does not pass them as inputs to the app. – zipper Jan 01 '23 at 07:14
3

Take a look to this page, it may help you: http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html

Specially, this part:

int getKeyCode()

Obtains the key code associated with this event. The key code identifies the particular key on the keyboard that the user pressed or released. The KeyEvent class defines many key code constants for commonly seen keys. For example, VK_A specifies the key labeled A, and VK_ESCAPE specifies the Escape key.

AJPerez
  • 3,435
  • 10
  • 61
  • 91
  • have been trying to use what you suggested but it seems something is wrong. when I want to use getKeyCode, I have to create an objrct from KeyEvent class which need to introduce some initial values...I do not know how to initialize it.....I should mention that I have changed my code architecture into two class that one of them contains main method. look at the folloing surce code: – msc87 May 25 '12 at 13:15
  • @msc87 You need to incorporate a `KeyListener`. It's Java's Swing way of monitoring keypresses. – David B May 25 '12 at 13:22
  • I have created an object "e" from KeyEvent class which need to introduce some initial values...I do not know how to initialize it.....I should mention that I have changed my code architecture into two class that one of them contains main method. look at the new version of my code above: – msc87 May 25 '12 at 13:29
  • 1
    @msc87 Refer to AardvarkSoup's answer for why you may have trouble grabbing ESC from your console application- I would recommend implementing a Swing GUI and using [a KeyListener](http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html). – David B May 25 '12 at 13:35
1

Note that Keylisteners may not always be what you are looking for. A more complete answer would also include a reference to adding keyBINDINGS which is a little more difficult to set up but also more versatile. So this is how one could do it.

First create a new class. If the coupled action requires params, set them up in your constructor. Let class extend AbstractAction so we can overwrite the ActionPerformed method.

public class UserAction extends AbstractAction {

String optionalParam;

UserAction(String optionalParam){
this.optionalParam = optionalParam;
}
@Override
public void actionPerformed(ActionEvent e) {

    System.out.println("Action Performed!");

    }

}

Then to call the action use the following. Note that getinputmnap takes a parameter integer that represents the status of focus of the object. The three valid options are "JComponent.WHEN_IN_FOCUSSED_WINDOW" "JComponent.WHEN_FOCUSSED" (which is default) & "JComponent.WHEN_ANCESTER_OF_FOCUSSED_COMPONENT".

JFrame graphicalUI = new JFrame();

JPanel panelWithKeybind = new JPanel();

Action userAction = new UserAction() //add params as constructor requires

panelWithKeybind.getinputmap(int 
focus_Status_Of_Panel).put(KeyStroke.getKeyStroke("ESCAPE"),"submit"); //Key
                                                                       
panelWithKeybind.getActionMap().put("submit",userAction);
Brakke Baviaan
  • 460
  • 3
  • 10