wood burning stoves
The moose likes Beginning Java and the fly likes Key listener or what? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Key listener or what?" Watch "Key listener or what?" New topic

Key listener or what?

Ola gharably

Joined: Jul 01, 2003
Posts: 10
Hi all,
I'm working on some program that should read any number, of course to some limit i know, and based on it do some operation.
Well I should enter this number from the keyboard without a textField or anything else. i.e. i should just when i press on any number ,for example number 20, and press Enter I want to store that value for later use. How can i do that?
Susilo Saja
Ranch Hand

Joined: May 27, 2003
Posts: 91
Hello Ola,
hope this example can help :
BufferedReader reader = new BufferedReader (new InputStreamReader (System.in));
System.out.print ("Enter number : ");
String sNumber = reader.readLine();
int iNumber = Integer.parseInt (sNumber);
Matt Fyffe

Joined: Jun 19, 2003
Posts: 25
I think he wants to use keylistener for it... so then for your class name you have
implements KeyListener
and then you must include the methods
public void keyPressed(keyEvent e)
public void keyTyped(KeyEvent e)
public void keyReleased(KeyEvent e)
The methods can all be blank except keyTyped if you just want to read the key, so in keyTyped you could do e.getKeyCode() which would tell you which key was pressed. If the key pressed was a number, then you could store it into an array. And if the key pressed was enter, it could proccess what was stored in the array.
As for how to check if they key pressed was a number, I think you can find the different variable constants at the sun java class listing.
Here's an example of using keyPressed in one of my progs:

Can anyone confirm if I'm right or not? I want to help other people but I think maybe I should stick to being helped .
[ July 07, 2003: Message edited by: Matt Fyffe ]
Ola gharably

Joined: Jul 01, 2003
Posts: 10
hi Fyffe,
your answer was really perfect.. u r absolutly right.. well i'm now using it in my program and its working perfect.. good luck Matt
I agree. Here's the link: http://aspose.com/file-tools
subject: Key listener or what?
It's not a secret anymore!