Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

read a single char 1

Status
Not open for further replies.

mackey333

Technical User
May 10, 2001
563
0
0
US
How would I go about reading a single character without requiring
Code:
[enter]
at the end? This is to make a "press any key to continue...." and also for an installation class that requires yes and no answers. I want to just be able to press y or n.

-Greg :-Q

flaga.gif
 
Excellent question!! But no answer at all...

If anyone knows i am also interested in knowing this

Momin ho to bay taigh bhee lerta hay sipahee
 
you need to use KeyListener. declare your class with something like:

public class myProg extends JPanel implements KeyListener{

...add the line:

addKeyListener(this);

to the constructor (if you didn't extend a component, then don't pass it 'this'). you will then need to add these methods to your program:

public void keyTyped(KeyEvent e){}
public void keyPressed(KeyEvent e){}
public void keyReleased(KeyEvent e){}

...you'll probably want to enter the code to continue in keyPressed. hint - use KeyEvent.getKeyCode (int), .getKeyChar (char), or .getKeyText (String) to identify which key has been pressed.
 
thanks, i'll try it out...will keylistener work on a console app? as i understood it, it only worked for guis.

-Greg :-Q

flaga.gif
 
yep, guis only; unless you wanted to rewrite component.addKeyListener for your non-component program.
 
Sure, it's easy with GUI to do it.
But I'm not sure that it can be done with java.

One suggestion is to use something like

"Press enter to continue..."
 
My last answer was wrong , this is the right one..

Sure, it's easy with GUI to do it.

But I'm not sure that it can be done with java and only console mode.

One suggestion is to use something like

"Press enter to continue..."

 
how about creating a JFrame with a KeyListener and then positioning it off the screen?

-Greg :-Q

flaga.gif
 
I tried that to, didn't work.

You need to set the new JFrame visible and then set focus to the the window.

And what if a computer dosen't run any GUI, then the program will not start after at all...
 
import java.io.IOException;
class readChar
{
public char getch()
{
try
{
return (char) System.in.read();
}
catch (IOException e)
{
System.out.println("error de io "+e);
}
catch(Exception e)
{
}
return 0;
}
public static void main(String args[])
{
char c = 0;
readChar readCharObj = new readChar();
while(c!=10)
{
c = readCharObj.getch();
}
}
}
Please give me a star if this text is useful.
Most of the code is provided by pedrosolorzano (Programmer) in
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top