473,672 Members | 2,497 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using KeyListener in a Loop

3 New Member
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 14350
JosAH
11,448 Recognized Expert MVP
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 New Member
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 Contributor
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(execu ted). 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,minimizin g the frame,keyboard press,released etc and etc) and then return/fire/show/updates the equivalent response(method s 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 Recognized Expert Contributor
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 New Member
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 Recognized Expert Contributor
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 New Member
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 Recognized Expert MVP
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 New Member
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
3986
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( Pk_myPrimaryKey INTEGER CONSTRAINT pk PRIMARY KEY DESCRIPTION 'This is the primary key of the table',
5
5981
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 TraceData) { instanceOfBinaryWriter.Write(d); }
9
3080
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 oItems" loop. After about 250 contacts, the program gives an InvalidCastException Error on the for each loop. I notice that Outlook's memory keeps increasing (using the task manager) until it reaches around 20,000K. When I run the program a second...
3
33361
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 code is here: foreach ( string propertyName in ht.Keys ) { this.setProperty( propertyName, ht );
2
5472
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 not even put the f into the textbox. However, the TextField does not appear to update until one keypress after I need it to. Eg. if I typed, 10fg, it would end up as "10f" then after the g, become "g10". I'm currently using the keyPressed...
4
1953
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 constructer game(),it's not working but when I extends JFrame it starts working & my problem is I have to extends JPanel ,so how can I solve it..... Here is the code import javax.swing.*; public class Game extends JPanel { public...
1
2819
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 tried several solution but none have worked. Heres the code public class Test extends Canvas implements KeyListener { static final int WIDTH =700; static final int HEIGHT =700; static final String TITLE ...
3
3427
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 object): public void setBattleController(Battle b){ this.addKeyListener(b); this.setFocusable(true); this.requestFocus(); } public void removeBattleController(Battle b){
2
3988
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 program and press keys, nothing happens. Any ideas? import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import...
0
8930
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8828
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8605
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8677
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6238
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5704
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4227
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4417
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1816
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.