Listening key events

Hello there,
I am trying to get the information of the key pressed on the keyboard. Following code works only for characters not for the arrow keys, alt, shift, F1 and etc...
Can you tell me what should I do?
Thanks.
Berk Can Celebisoy
class MyKeyEvents implements KeyListener
public void keyTyped(KeyEvent e) {
System.out.println(e.getKeyChar());
public void keyReleased(KeyEvent e) {
public void keyPressed(KeyEvent e) {
}

The KeyTyped event is only generated for displayable characters. KeyPressed/KeyReleased events are generated for all key strokes.
Read the KeyEvent API for more information.

Similar Messages

  • How to listen a key event without having any window component

    Hi all,
    I would like to know how can I listen key events from an application that doesn't use windows
    Thanks

    yoiu can make a Thread run inside your application. This will listen for inputs in the command line. For examplethis is part of a chat server (on the console) with let the server manager to enter messages or commands.
    The message or command entered on the console by the user is catched and processed as a String. The string is passed to the processConsole() method, you must define yourself.
    Th Thread is never stopped, so the user may enter any message at any time
    The core of you application should also be a Thread for better performance, but maybe it will also work without. Jst try and provide needed importstatements.
    Runnable runInput = new Runnable() {
            public void run() {
              while(true) {
                try {
                  byte buffer[] = new byte[255];
                  System.out.print(prompt);
                  System.in.read(buffer);//, 0, 255);
                  String inputString = new String(buffer, "Default");
                  processConsole(inputString);
                catch(NullPointerException npe) {
                  System.out.println("Syntax error");
                catch(Exception e) {e.printStackTrace(); }
          Thread inputThread = new Thread(runInput);
          inputThread.start();

  • Listening Tab Key Event On JTextField

    Hi
    i am unable to listen Tab Key Event on JTextField ....
    tField.addKeyListener(new KeyAdapter()
    public void keyPressed(KeyEvent e)
    if (e.getKeyCode()==e.VK_TAB)
    JOptionPane.showMessageDialog(null,"Tab Pressed");
    else
    JOptionPane.showMessageDialog(null,"Tab Not Pressed");
    When i pressed Tab Key then it dont come in KeyPressed Event ...Actually it go towards next FocusAble component ..
    Any help in this regard.....

    I also Checked it by using
    tField..setFocusTraversalKeysEnabled(false);
    tField.addKeyListener(new KeyAdapter()
    public void keyPressed(KeyEvent e)
    if (e.getKeyCode()==e.VK_TAB)
    JOptionPane.showMessageDialog(null,"Tab Pressed");
    else
    JOptionPane.showMessageDialog(null,"Tab Not Pressed");
    In this case each time e.getKeyCode() returns 0...
    plz help me

  • How to listen key board event

    Hi,
    I want to trap CTRL key event on panel on windows plateform plz send a sample code...
    Thanks

    Did you do some follow-up research on the suggestions given to you by tjacobs01 in your last posting on this subject?
    http://forum.java.sun.com/thread.jspa?threadID=645822

  • Detect key events on anything

    If I have a JFrame with many components on it, how do I detect if a key is pressed, without having to add a listener to every component? For example, how can I check for the escape key being pressed, but not having to have componentN.addKeyListener(this); for everything?
    Thanks
    US101

    The correct way to collect the key events is the following:
    from java 1.2 to java 1.3 use the FocusManager. This class can be found in the javax.swing package. You would then need to extend the DefaultFocusManager and override specific behavior.
    for java 1.4 use the KeyBoardFocusManager. This class can be found in the java.awt package.
    Please see the following for a better explanation:
    http://java.sun.com/j2se/1.4/docs/api/java/awt/doc-files/FocusSpec.html
    Thanks for your time,
    Nate

  • Catching key events in application

    I have a JFrame with a JDesktop containing lots of JInternalFrame with various of components such as JTextFields etc.
    Now, i want to have a "main" listener that will catch key events no matter which component that has focus. For example pressing CTRL+A should produce something in the application no matter which component that has focus.
    How do I implement this in an easy way?

    It doesnt seem to work to add a KeyListener to the JFrame...
    this.addKeyListener(new KeyAdapter(){
                   public void keyTyped(KeyEvent e){
                        System.out.println("KeyTyped()");
                   public void keyPressed(KeyEvent e){
                        System.out.println("KeyTyped()");
              });Adding that to the JFrame gives nothing to System.out when a JTextArea inside an JInternalFrame has focus.

  • KEY events in MIDlets

    Hello all,
    I am basically new to J2ME MIDP development and also new to this
    forum. So apologies if this has already been covered or turns out to
    be a stupid question :) Here goes:
    I am trying to develop a MIDlet where I have a Form to accept certain
    values from the user. This is fairly straightforward and is easy to
    create with the high level Form a and TextField objects.
    Now, I wish to add a functionality to my MIDlet, in which, the user
    can press a specific key.. say the "Select" key or the "Call" key.. at
    any time during the form to start another thread of operation which
    performs something totally different... say for example, the user is
    entering values into the form and in between somewhere he presses this
    specific key and the phone start playing music. I hope you get my
    point.
    Basically I want to listen for key pressed or key held events on a
    Form object. Now I understand that Key events can be found only on the
    low-level Canvas based UIs. So is it possible to do it with Screen class
    elements..?
    Thanks,
    Nik

    You can try to use a CustomItem. What events will be delivered to the custom item depends on the implementation, though. Also these events will be only delivered when the CustomItem is focused.
    Have a look at the J2ME Polish GUI for using CustomItems for MIDP/1.0 devices as well.
    http://www.j2mepolish.org
    Best regards,
    Robert

  • How to consume key events

    I would like to create a subclass of TextBox that only allows numeric input. My idea was to provide my own onKeyType() handler and consume any key events that do not correspond to digits. However, I can't find any way to consume key events from further processing. How do I do this?
    Are there any other suggestions how to accomplish the task of providing your own filter concerning valid key input?
    /Bengt

    I also wanted a kind of validators for the TextBox class of JavaFX. So I've tried solving the problem using the SwingTextField class and some Java APIs. The following is my code for a SwingTextField accepting only digits, but I do want it to be much simpler.
    import java.awt.AWTEvent;
    import java.awt.event.AWTEventListener;
    import java.awt.event.KeyEvent;
    import java.awt.Toolkit;
    import javafx.ext.swing.SwingTextField;
    import javafx.scene.Scene;
    import javafx.stage.Stage;
    import javax.swing.JComponent;
    class DigitKeyEventHookListener extends AWTEventListener {
        public-init var  source:JComponent;
        public  override function  eventDispatched( event:AWTEvent):Void {
            if (event.getSource().equals(source)) {
                var keyEvent : KeyEvent = event as KeyEvent;
                var keyCharacter = keyEvent.getKeyChar();
                var isDigit = false;
                var code = keyEvent.getKeyCode();
               if ((KeyEvent.VK_0 <= keyCharacter) and (keyCharacter <= KeyEvent.VK_9)) {
                       isDigit = true;
                if ((code ==KeyEvent.VK_DELETE) or (code ==KeyEvent.VK_BACK_SPACE)) {
                    isDigit = true;
                if ((code ==KeyEvent.VK_LEFT) or (code ==KeyEvent.VK_RIGHT)) {
                    isDigit = true;
               if (not isDigit) {
                    keyEvent.consume();
    function createSwingTextField() : SwingTextField{
        var field = SwingTextField {
            columns:12
        var listener =  DigitKeyEventHookListener{
            source: field.getJTextField()
        Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.KEY_EVENT_MASK);
        return field;
    Stage {
        title: "Digit Box"
        width: 200
        height: 80
        scene: Scene {
            content: createSwingTextField()
    }

  • Flex4.5 SDK under Flash builder Burito doesnt dispatch Enter key event in Text Area anymore

    Flex 4.5 under Flash builder Burito doesnt dispatch 'Enter' key event in Text Area anymore, in prev version 4.1 it was working properly, this stopped working after migration to Burito + Flex SDK 4.5?
    What that suppose to be?

    Hi
    That's true that Flex4.5 SDK under Flash builder Burito doesn't listen Enter key in Text Area for KeyUp or KeyDown event.
    Here I found a work around you can use.
    Add an eventlistener to the component in actionscript and set the useCapture=true next to eventlistener function. Now you can listen enter key for KeyUp or KeyDown Event
    Hope this helps
    Rush-me

  • JPanel can't receive key events

    I have a single JPanel added to the content pane of a JFrame.
    I want to itercept key events by adding a KeyListener to the JPanel.
    If I do it, I don't receive key events.
    To solve the problem I identified two ways:
    - add the KeyListener to the JFrame's content pane
    - invoke setFocusable(true) on the JPanel (available only since 1.4)
    I can't use the former because I want to bind the the KeyListener to the JPanel, and I can't use the latter because I don't want to have dependencies on jdk 1.4.
    Can anyone suggest a way to solve the problem as simple as calling setFocusable() but available also for older versions of java?

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class KeyListenTest {
         public static void main(String[] args) {
              JPanel panel = new JPanel();
              panel.addKeyListener(new KeyAdapter() {
                   public void keyTyped(KeyEvent e) {
                        System.out.println(e);
              JFrame frame = new JFrame();
              frame.getContentPane().add(panel);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(400,300);
              frame.setVisible(true);
              panel.requestFocus();
    }The panel must be displayable and visible, so you have to make the call after frame.setVisible(true), however if you don't have any other components that will take the focus away from your panel, this should do it for you. If you want the use to be able to shift focus to your panel, then just add a mouse listener to the panel with a mousePressed(MouseEvent) method that calls the requestFocus() method on the panel.

  • Getting key events without a jcomponent...

    Is it possible to get key events without adding a keylistener to a jpanel? I want a class of mine to manage input of it's own, but it has no reference to a jpanel. They don't necessarily have to be KeyEvents, but just some way to detect if a key has been pressed (like the arrow keys). How can I do this? Thanks.

    Lots of components can listen for key events.
    What does your class subclass?It doesn't subclass anything. I am creating a custom menu system for my game using images I have made for the tileset. I would like it to handle some keyboard events of its own. (Like if the down arrow is pressed, it will move the focus down to the next component on its own). Right now I am currently passing the key events from my fullscreen jpanel to the menu class and it is handling them that way. Thanks.

  • Key events & Combinations of keys

    Hi,
    I'm listening to key events and it's fine one one key is pressed;
    if (event.getKeyCode() == KeyEvent.VK_UP)
    }But I need to know when a combination of keys is pressed (like ctrl-a). How can I know if two specifics keys are pressed together?
    Thank you...

    Read JavaDoc. java.awt.event.InputEvent class.
    if (event.getKeyCode() == KeyEvent.VK_UP && event.isControlDown())
    }

  • Key event handler

    What is the best approach to handling key events (listening for keys being pressed)?
    Are there any widgets out there for this purpose? Just do it in JavaScript?
    Thanks

    The best 'approach' for key events in Captivate e-learning courses is to avoid them as much as possible.  They are a can of worms because every browser is different in terms of which keystrokes it will allow you to use.  So you may find that you can use certain keystrokes in one browser but only some of them will work in another.
    Widgets are not the answer because they are ActionScript and AS calls are close to the bottom of the pile.  JavaScript will also only get you so far because even that happens AFTER the browser gets first pick.

  • Sevice Contract - Listener for Events Queue Issue

    Hi,
    The Listener for Events Queue in our Production environment ran very long, It took about 3+ hrs to complete the program. Is there any thing specific that we can check as part of RCA.
    Further there were 'library cache lock' found ... how this can impact the performance and how library cache lock works.
    Regards
    Tauseef E Ahmad

    Hi Team,
    i used the following code for recognizing the key events.
    String javaScriptKeyListener =
    " function keyListener() "
    +" { "
    +" alert(window.event.keyCode) ; } ";
    OAWebBean body = pageContext.getRootWebBean();
    if (body instanceof OABodyBean)
    ((OABodyBean)body).setOnLoad("onKeyPress = javascript:keyListener()");
    but it is not working as expected..
    Any suggestions ??
    Regards
    Sridhar

  • Something is eating my key events!

    Okay, so I am trying to add some key events to a game. I have added this listener to a class I called Background:
              this.addKeyListener(new java.awt.event.KeyAdapter() {
                   public void keyPressed(java.awt.event.KeyEvent e) {
                        System.out.println("A key was pressed");
                        backgroundpanelKeyPressed(e);
                   public void keyReleased(java.awt.event.KeyEvent e) {
                        System.out.println("A key was released");
                        backgroundpanelKeyReleased(e);
    And then the code for my key events is as follows:
         // pressing the arrow button will allow the ship to move
         public void backgroundpanelKeyPressed(java.awt.event.KeyEvent e) {
         System.out.println ("In Here!");
         switch(e.getKeyCode()) {
         case KeyEvent.VK_LEFT:
         System.out.println("Left key pressed");
         break;
         case KeyEvent.VK_DOWN:
         System.out.println("Down key pressed");     
         break;
         case KeyEvent.VK_UP:
         System.out.println("Up key pressed");     
         break;
         case KeyEvent.VK_RIGHT:
         System.out.println("Right key pressed");     
         break;
                   // releasing the arrow button will stop the ship from moving
         public void backgroundpanelKeyReleased(java.awt.event.KeyEvent e) {
         switch(e.getKeyChar()) {
         case KeyEvent.VK_LEFT:
         System.out.println("Left key released");
         break;
         case KeyEvent.VK_DOWN:
         System.out.println("Down key released");
         break;
         case KeyEvent.VK_UP:
         System.out.println("Up key released");
         break;
         case KeyEvent.VK_RIGHT:
         System.out.println("Right key released");
         break;
    I can't find the problem with any of that, but something is intercepting my key events before they even get there. Pressing the arrow keys does nothing, but if I hit the spacebar, then it calls Background's constructor.
    I searched through the entire code, and nowhere is there any key listener, or any reference to the Background class aside from where I am actually trying to call it.

    Does your program always react when you press space? Because if it didn't I'd guess you have problems with the event focus (or whatever it's called). Let's say you add your KeyListener to the Frame/Applet your game is displayed in. At some stage during gameplay a java.awt.Button is pressed. The button will keep the focus and subsequent keypresses will be reported solely to it, so your KeyListener has to listen at the button, too (or you can do a requestFocus() for the component you want to listen to, whenever it looses focus. See FocusListener on this).

Maybe you are looking for

  • The 4 or 5 finger gesture does nothing on my iPad 1. Why?

    I've read the manual in the over view and don't see that it is only applicable to iPad 2...

  • Help with html files when placing Web Content overlay

    Hi there, We have an educational app with lots of interactive exercises - all of which were initially designed in Flash. I have converted the fla files into hmtl using Wallaby. For each fla file, Wallaby creates a js, css and html file as well as an

  • Question re SIM card - selling iphone

    Have canceled AT&T contract and am selling 3Gs. Should I remove SIM card before selling or does it even matter? Thanks.

  • Multiple Logon disable

    Dear All , while multiple logon are performed.SAP pop-up a message with 3 options 1.terminate logon 2.continue with the logon 3.continue with the logon terminating other sessions. Here we Want to disable the 2 option that is : continue with the logon

  • Unable to configure SMTP settings in OATS admin

    Hello, I have installed OATS 9.20 in my pc,when i tried to configure SMTP settings in OATS admin,it is not working and giving an error message "error while sending mail"when i clicked "Test Mail".Can any help me in this?