how can i code a java program that detects my keystroke?
for example i press enter,
the program will display a string message "You Press Enter" + "<Enter key>"
is it possible to make this algorithm in java?
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
how can i code a java program that detects my keystroke?
for example i press enter,
the program will display a string message "You Press Enter" + "<Enter key>"
is it possible to make this algorithm in java?
Check out the robot class, that should do the trick
You can use a KeyListener. You need to have some object that listens for the event, ordinarily a Component (JFrame in the example below) in which you can call addKeyListener(KeyListener) to add the KeyListener implementation.
public class Test extends JFrame implements KeyListener{ /**Constructor*/ public Test(){ super(); addKeyListener(this); setVisible(true); } /**Key Listener implementation*/ public void keyPressed(KeyEvent e){ System.out.println("Key Pressed"); } public void keyReleased(KeyEvent e){} public void keyTyped(KeyEvent e){} public static void main(String[] args) { new Test(); } }
public void keyPressed(KeyEvent e){ int id = e.getID(); String keyString; if (id == KeyEvent.KEY_TYPED) { char c = e.getKeyChar(); keyString = "key character = '" + c + "'"; // this part } else { int keyCode = e.getKeyCode(); keyString = "key code = " + keyCode + " (" + KeyEvent.getKeyText(keyCode) + ")"; } System.out.println(keyString); }
sir the method only displays an uppercased character ,, if i pressed a lower case character it always
display it as an uppercased.