473,390 Members | 1,454 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,390 software developers and data experts.

Using KeyListener in a Loop

3
I am relatively new to Java, so please excuse me if I'm not specific enough. I am making a program where a large portion of it is just one big while loop, and I want to be able to read specific keys being pushed to invoke different commands and methods, but apparently KeyListener doesn't work inside of a loop. Is there another, relatively simple way for me to read keyboard input?
Oct 26 '08 #1
9 14302
JosAH
11,448 Expert 8TB
I am relatively new to Java, so please excuse me if I'm not specific enough. I am making a program where a large portion of it is just one big while loop, and I want to be able to read specific keys being pushed to invoke different commands and methods, but apparently KeyListener doesn't work inside of a loop. Is there another, relatively simple way for me to read keyboard input?
If you're using Swing you have to 'invert' your logic, i.e. your program is not in
control as long as the user doesn't do anything. Your program doesn't wait or
run in a while loop. It's one special thread the EDT (Event Dispatch Thread) that
does the waiting (and painting of visual components if needed) and fires an
event to a registered Listener when the user causes that event.

Basically you register your KeyListener to some component and don't do anything
at all. When the user presses a key the EDT fires an event and your Listener will
be activated. Only then does your program do something: it should quickly do
something as long as it runs in the EDT or start another thread that does the job.

A lot of people make that mistake: they process whatever they have to process
in the EDT which ties that thread to your business logic; it is supposed to check
for events and repaint visual components instead. As long as its busy for your
purposes it can't pay any attention to user gestures and your application seems
to respond sluggish.

kind regards,

Jos
Oct 27 '08 #2
zakwiz
3
Thank you a lot for your help, but unfortunately I am VERY new to Java, and though you obviously know what you're talking about, I don't really get it. I would really appreciate it if you or someone else explained it in simpler terms. Thanks!
Oct 28 '08 #3
sukatoa
539 512MB
when using Graphical User Interface in your application,

let say, that component(Frame,Dialog etc) throws another thread that handles a while loop started after it was activated(executed). Its job is to show whatever instructions you've setup(coded GUI, unless you call the dispose() method, where that method stops showing the interface and not the thread itself),waits for any event(clicking the mouse,minimizing the frame,keyboard press,released etc and etc) and then return/fire/show/updates the equivalent response(methods under the specific listeners that implements the EventListener are called directly after any event is fired, ex. clicked)....see the Java API Documentation.

I prefer to code directly with the sample code from java tutorials with the API Documentation and OBSERVE its behavior if i don't understand what the book says than trying to grasp what the content(book) says to the readers.... (some theories are came from experiments)....

regards,
sukatoa
Oct 28 '08 #4
chaarmann
785 Expert 512MB
Thank you a lot for your help, but unfortunately I am VERY new to Java, and though you obviously know what you're talking about, I don't really get it. I would really appreciate it if you or someone else explained it in simpler terms. Thanks!
It is called "polling" what you are trying to do:
Expand|Select|Wrap|Line Numbers
  1. Scanner keyboard = new Scanner(System.in);
  2. do
  3. {
  4.    String input = keyboard.nextLine();
  5.    System.out.println("You just typed:" + input);
  6. } while (! input.equals("END"))
  7.  
Here, the running thread waits inside the loop until you inserted a line and pressed return. Only then it executes the next command.

It is called "interrupt" what you need to do. This is the common case in event handling:
That means, the system itself looks from outside at your functions you have written and whenever it detects one that handles the keyboard input, it just calls it. You only have to write the function, nothing else. And if you press a second button while your first function is still running, your function is called again and runs in parallel to your first one (as a second thread). This parallel run is not possible if you use "polling" as written above.
Look at this example:
Expand|Select|Wrap|Line Numbers
  1. public class KeyEventDemo ...  implements KeyListener ... {
  2.     ...//where initialization occurs:
  3.     typingArea = new JTextField(20);
  4.     typingArea.addKeyListener(this);
  5.     ...
  6.  
  7.     /** Handle the key-pressed event from the text field. */
  8.     public void keyPressed(KeyEvent e) {
  9.     System.out.println(("You just typed:" + e.getKeyChar());
  10.     }
  11.  
Please note that the function keyPressed() is called by the system. You don't call it yourself!

I hope this explanation makes it clearer for you.
Oct 28 '08 #5
zakwiz
3
chaarmann, I think you have it backwards, I'm doing it the way you show it called interrupting, as I have and have added a KeyListener and have code in the keyTyped method. It works fine elsewhere in the program, but within a while loop it just doesn't respond at all to typing, even if i press enter afterwards.
Oct 28 '08 #6
chaarmann
785 Expert 512MB
chaarmann, I think you have it backwards, I'm doing it the way you show it called interrupting, as I have and have added a KeyListener and have code in the keyTyped method. It works fine elsewhere in the program, but within a while loop it just doesn't respond at all to typing, even if i press enter afterwards.
I don't get it. Why do you need a while loop if you use KeyListener? The whole point in my explanation is that you don't need a while loop there at all.

Do you want to concatenate all the typed letters to a string and then only print it if a user pressed return? For that you don't need a while loop. You can do it with a static variable. Like here:

Expand|Select|Wrap|Line Numbers
  1. public class KeyEventDemo ... { 
  2.     ... 
  3.     static String typedCharacters = "";
  4.     ...
  5.     public void keyTyped(KeyEvent e) {
  6.       int keyCode = keyEvent.getKeyCode();      
  7.       if (keyCode == 13) { // 13 = return-key
  8.          System.out.println("You just typed:" + typedCharacters);
  9.          typedCharacters = "";
  10.       }
  11.       else typedCharacters +=  e.getKeyChar();
  12.     } 
REMARK:
This code does not take in mind parallel threads. So it only works if you don't type too fast. If you want to make it thread-save, then you have to use synchronisation mechanisms, which would make this sample code more complicated and less understandable.

I am curious what you want to achieve in your while-loop. Did I guess right?
It would be of great help if you show us your while-loop you have written so far.
Oct 29 '08 #7
Sarii
7
You could always just use a switch case. I don't know much about java, but that's what I would do! Even though the code would be relatively long and repetitive, it'll work out the way you want it to.
Oct 29 '08 #8
JosAH
11,448 Expert 8TB
You could always just use a switch case. I don't know much about java, but that's what I would do! Even though the code would be relatively long and repetitive, it'll work out the way you want it to.
I'm sorry, I don't see any use for a switch() statement here; care to elaborate?

kind regards,

Jos
Oct 29 '08 #9
Sarii
7
Expand|Select|Wrap|Line Numbers
  1. switch(key)
  2.         {
  3.             case 'a': System.out.println("You typed A");
  4.             break;
  5.             case 'b': System.out.println("You typed B");
  6.             break;
  7.             case 'c': System.out.println("You typed C");
  8.             break;
  9.             case 'e': System.out.println("You typed E");
  10.             break;
  11.             default: System.out.println("Invalid key type");
  12.             break;
  13.  
I was thinking along the lines of this...but maybe not..? Lol.
Dec 4 '08 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

8
by: doomx | last post by:
I'm using SQL scripts to create and alter tables in my DB I want to know if it's possible to fill the description(like in the Create table UI) using these scripts. EX: CREATE TABLE(...
5
by: John Dumais | last post by:
Hello, I have been trying to figure out how to write an array of doubles (in this specific case) to a binary stream without using a loop. What I have been doing is... foreach(double d in...
9
by: George McCullen | last post by:
I have an Outlook 2003 using Exchange Server 2003 Public Contacts Folder containing 20,000 Contacts. I am writing a VB .Net 2003 program that loops through all the contacts in a "for each oCt in...
3
by: Akira | last post by:
I noticed that using foreach is much slower than using for-loop, so I want to change our current code from foreach to for-loop. But I can't figure out how. Could someone help me please? Current...
2
jkmyoung
by: jkmyoung | last post by:
I was trying to create an applet with a TextField that would only accept an integer, and ignore any other keystrokes. Eg, if a user typed in an 'f' into the field, the TextField should ignore it, and...
4
by: pankajs | last post by:
Hello freinds! I am developing a game & a problem occur with pressing the keys the class name is game it extends JPanel, when I register keylistener by writing addKeyListener(this); in the...
1
twitch3729
by: twitch3729 | last post by:
Basicaly, I have a frame with only a Canvas on it and a KeyListener. For some reason the keyListener stops registering my keys as soon as I have moved the Window from its starting position. I have...
3
by: Humakt | last post by:
I've done KeyListener before successfully, but for some reason I can't get it to work in my recent project. Here is the code: View class (setBattleController is called upon creating new Battle...
2
mrjohn
by: mrjohn | last post by:
Hey, I'm trying to make a program that will recognize when certain keys are released, so that I can encorperate it into a game I'm making. Unfortunately, it doesn't seem to be working. When I run the...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.