• Advertisement
Sign in to follow this  

[java] Wait for User to Press Enter

This topic is 4181 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I know that this seems really stupid, but what code is necessary for a Java program to wait until the user presses enter after some text is displayed? There just does not seem to be any working resources on this at all. Thanks in advance for any help.

Share this post


Link to post
Share on other sites
Advertisement
The class must implement KeyListener and one of the first few lines of code must be "addKeyListener(this);" (Without the quotes). You must include the void methods keyPressed(KeyEvent e), keyTyped(KeyEvent e), and keyReleased(KeyEvent e).
In the keyPressed (or keyReleased, your preference) method you must have the code
if(e.getKeyCode()==10)//10 is the keyCode for enter.
closeText();//Put what you want to do when they hit enter here.

Share this post


Link to post
Share on other sites
Just a tip:
Never use literals to represent key values (or any event, for that matter). These could change in a future version of Java. The preferred approach would be KeyEvent.VK_ENTER .

Share this post


Link to post
Share on other sites
OK, I've tried using all of the stuff you gave me and implement it into a simple Hello World demo first, but it won't compile because of an "illegal start of expression" at line 6. Here is my code:

public class KeyStrokeTest implements KeyListener{
public static void main (String[] args) {
//KeyStroke code
addKeyListener(this);

void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER) {
closeText();
}
}
void keyTyped (KeyEvent e) {}
void keyReleased (KeyEvent e) {}

System.out.println ("Hello World!");
}
}

Share this post


Link to post
Share on other sites
You are trying to nest those functions inside of the main function. I don't beleive Java supports nested functions. They should be in the class but not the main function.

public class KeyStrokeTest implements KeyListener
{
void keyPressed(KeyEvent e)
{
if (e.getKeyCode()==KeyEvent.VK_ENTER)
{
closeText();
}
}

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

public static void main (String[] args)
{
//KeyStroke code
addKeyListener(this);

System.out.println ("Hello World!");
}
}

Share this post


Link to post
Share on other sites
Quote:
Original post by Simian Man
You are trying to nest those functions inside of the main function. I don't beleive Java supports nested functions. They should be in the class but not the main function.

public class KeyStrokeTest implements KeyListener
{
void keyPressed(KeyEvent e)
{
if (e.getKeyCode()==KeyEvent.VK_ENTER)
{
closeText();
}
}

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

public static void main (String[] args)
{
//KeyStroke code
addKeyListener(this);

System.out.println ("Hello World!");
}
}


Thanks for the help, but will I have to do anything in particular if it's in an applet as that's what it's eventually going to be placed in? Also the code you game me does not compile either.

Share this post


Link to post
Share on other sites
Hi, Is it a console app?

Because this will work just fine.

public static void main(String[] args) {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter somethin:\nasd");
try {
String str = r.readLine(); //will wait for a new line;
} catch (IOException e) {
e.printStackTrace();
}
}


The function readline of BufferedReader wait for a new line to continue. In our case enter would be a newline. I have not tested that on unix but I'm pretty sure it can work!

Share this post


Link to post
Share on other sites
GTspeed is correct in his code (just missing "the rest of the story" like components and windows and such. Here is a better tutorial that should help:

http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html

Good luck.

Share this post


Link to post
Share on other sites
Well if you want to use it in an applet here is a quick helloworld applet with the additional functionality you are looking for.



import java.awt.*;
import java.awt.event.*;
import javax.swing.JApplet;

public class HelloWorldApplet extends JApplet implements KeyListener {

private boolean displayText;

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

public void init() {
displayText = true;
}

public void paint( Graphics g ) {
if( displayText )
g.drawString("Hello World!",10,10);
else
g.clearRect(0,0,this.getWidth(),this.getHeight());
}

public void keyPressed( KeyEvent e ) {

}

public void keyReleased( KeyEvent e ) {
if( e.getKeyCode() == KeyEvent.VK_ENTER ) {
displayText = !displayText;
this.paint(this.getGraphics());
}
}

public void keyTyped( KeyEvent e ) {
//mainly used for standard editing characters
}

}






Now the source for the page that will display the applet

<html>
<head>
<title>Hello World Applet Test Page</title>
</head>
<body>
<applet
code="HelloWorldApplet"
width="400"
height="400">
If you are seeing this text you need to download
<a href="http://java.sun.com/">Java</a>
in order to properly view this web page.
Please, follow the link provided!
</applet>
</body>
</html>


I compiled and tested it and it works! Hope that helps!

Share this post


Link to post
Share on other sites
Quote:
Original post by Simian Man
You are trying to nest those functions inside of the main function. I don't beleive Java supports nested functions. They should be in the class but not the main function.

This is true, but where did this "nested function" concept come from? Does C++ support nested functions? If so, how are they used?

Share this post


Link to post
Share on other sites
Quote:
Original post by Lukewarm
Quote:
Original post by Simian Man
You are trying to nest those functions inside of the main function. I don't beleive Java supports nested functions. They should be in the class but not the main function.

This is true, but where did this "nested function" concept come from? Does C++ support nested functions? If so, how are they used?

I'm very sure that C++ does not support nested functions. The only language that I know of that supports nested functions is Ada. There are a couple of other languages that I am sure support nested functions.

Java does support nested classes however and also anonymous classes which you could use to do the Event listeners like the following.

this.addKeyListener(
new KeyAdapter() {
public void keyReleased( KeyEvent e ) {
if( e.getKeyCode() == KeyEvent.VK_ENTER ) {
displayTest != displayText;
this.paint( this.getGraphics() );
}
}
}
);

Very useful for Event listeners and similar things.

Share this post


Link to post
Share on other sites
Quote:
Original post by Lukewarm
Quote:
Original post by Simian Man
You are trying to nest those functions inside of the main function. I don't beleive Java supports nested functions. They should be in the class but not the main function.

This is true, but where did this "nested function" concept come from? Does C++ support nested functions? If so, how are they used?


C++ does not either, but Pascal and Python do. I wasn't sure if he really meant to make them nested or if it was just a typing error.

Share this post


Link to post
Share on other sites
Quote:
Original post by 5MinuteGaming
Quote:
Original post by Lukewarm
Quote:
Original post by Simian Man
You are trying to nest those functions inside of the main function. I don't beleive Java supports nested functions. They should be in the class but not the main function.

This is true, but where did this "nested function" concept come from? Does C++ support nested functions? If so, how are they used?

I'm very sure that C++ does not support nested functions. The only language that I know of that supports nested functions is Ada. There are a couple of other languages that I am sure support nested functions.

Java does support nested classes however and also anonymous classes which you could use to do the Event listeners like the following.

this.addKeyListener(
new KeyAdapter() {
public void keyReleased( KeyEvent e ) {
if( e.getKeyCode() == KeyEvent.VK_ENTER ) {
displayTest != displayText;
this.paint( this.getGraphics() );
}
}
}
);

Very useful for Event listeners and similar things.

Yes, it's elegant to code, but doesn't that add a lot of extra overhead?

Share this post


Link to post
Share on other sites
Quote:
Original post by Lukewarm
Quote:
Original post by 5MinuteGaming
Quote:
Original post by Lukewarm
Quote:
Original post by Simian Man
You are trying to nest those functions inside of the main function. I don't beleive Java supports nested functions. They should be in the class but not the main function.

This is true, but where did this "nested function" concept come from? Does C++ support nested functions? If so, how are they used?

I'm very sure that C++ does not support nested functions. The only language that I know of that supports nested functions is Ada. There are a couple of other languages that I am sure support nested functions.

Java does support nested classes however and also anonymous classes which you could use to do the Event listeners like the following.

...

Very useful for Event listeners and similar things.

Yes, it's elegant to code, but doesn't that add a lot of extra overhead?

Only as much overhead as if you were to create a separate class which isn't very much at all. This code simply creates a subclass of KeyAdapter and returns the reference to that subclass to the addKeyListener(); method. Anonymous classes are the same as regular classes but don't require a full declaration such as public class <identifier>. You can assign them to a variable for example:

KeyListener myListener = new KeyAdapter() {
public void keyReleased( KeyEvent e ) {
if( e.getKeyCode() == KeyEvent.VK_ENTER ) {
displayTest != displayText;
this.paint( this.getGraphics() );
}
}
}
);

//and then assign it or pass it as a normal class
this.addKeyListener( myListener );

The compiler will create a separate .class file for all Anonymous classes with the parent class name and a $ then a number increasing in the order in which they are declared starting at 1. The key adapter class is an empty implementation of the KeyListener and is a convenience class meant for exactly this sort of input handling. You can create and anonymous class from KeyListener itself but you have to implement all the functions defined in the interface thus the Java API provides KeyAdapter. Inner classes handled similarly where the file name is the encapsulating class name followed by $ sign and the name of the inner class.

P.S. I did some research into the performance of anonymous classes and the only thing that I could find about any problems was an article back in 2000 which suggested that the problem had already been fixed and I'm confident in saying that the newer version of java do not have a performance hit for anonymous classes over creating a separate subclass. Here is a link to the article for those that are curious
http://www.javaspecialists.co.za/archive/Issue002.html

Share this post


Link to post
Share on other sites
Just for completness, Java supports inner, nested and anonymous classes. My favorite language features of Java :-)


class MyClass {

String myAttribute = "Class";

// inner class / interface
interface Bar {
void bar();
}

void anonymous() {

// anonymous class - one instance
Bar bar = new Bar() {

String myAttribute = "Anonymous";

public void bar() { System.out.printf("%s : %s\n", MyClass.this.myAttribute, myAttribute); }
};
}

void nested() {

// nested class
class Foo implements Bar {

String myAttribute = "Nested";

public void bar() { System.out.printf("%s : %s\n", MyClass.this.myAttribute, myAttribute); }
}

// multiple instances
Bar bar0 = new Foo();
Bar bar1 = new Foo();
}

}



What I know about performance is, that all are almost equal. Although the Java VM may benifit from the information that anonymous classes can only have one instance and nested classes can only be instanced within the method.

However, all three consume sightly more memory, because they contain implicit references to all their wrapping classes. The only exception are inner classes, because they can be declared 'static'. With this modifier they can be instanced without an instance of their wrapping class, but therefore you cannot acces its attributes and methods.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement