Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Java (http://www.programmingforums.org/forum17.html)
-   -   Keypress question from a somewhat new Java programmer (http://www.programmingforums.org/showthread.php?t=14805)

sibelius7 Dec 25th, 2007 2:23 PM

Keypress question from a somewhat new Java programmer
 
Hi there...

I believe that my question is somewhat simple, but as my thread title suggests, I'm a little new at Java programming.

My problem is that I need to know how register keypresses somehow with Java. I plan to use this as a component of part of a senior project (which is basically a very simple music composition program which saves files in .mid format) for my computer science class which. This is the only component of the program so far that I havent had any progress in, and seeing as it's winter break now... I might as well use this time wisely.

All I need is to figure out how to do the following... in code of course:

If the a-key is pressed, perform action x.

I have read a little and heard about keypress listening, and code that sits in an seemingly-infinite loop that only terminates upon the press of a certain key, but I just don't know how to implement it.

Any help at all would be appreciated

Thanks :twisted:

andro Dec 25th, 2007 2:54 PM

Re: Keypress question from a somewhat new Java programmer
 
This should help :)

http://java.sun.com/j2se/1.5.0/docs/...yListener.html

http://java.sun.com/docs/books/tutor...ylistener.html

sibelius7 Dec 25th, 2007 5:11 PM

Re: Keypress question from a somewhat new Java programmer
 
Well that's helpful... I swear I looked in .awt.

Thanks a lot andro, now I have something to go with!

(that doesnt mean I dont need any more advice haha)

Jimbo Dec 25th, 2007 7:04 PM

Re: Keypress question from a somewhat new Java programmer
 
Some people also prefer to use the KeyAdaptor class as it doesn't require you to implement all the methods in the KeyListener interface.

null_ptr0 Dec 26th, 2007 9:58 AM

Re: Keypress question from a somewhat new Java programmer
 
Here's some pseudocode I whipped up:
:

import java.io.InputStream;

public class Test {
  private InputStream stdin = System.in;

  public char get() {
      return (char) stdin.read();
  }

  public void loop() {
      while(true)
        if(get() == 'a')
            launchEvents();
  }

  /* Implement your code here */
  protected void launchEvents() { }

  public static void main(String[] argv) {
      loop();
  }
}

That is, if your using the console.
If you are using a GUI, then search KeyListener, addKeyListener, and KeyEvent.


All times are GMT -5. The time now is 9:33 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC