Using InputMap and ActionMap to detect any key pressed...plz help

Hi,
I am quite new to Java. I have a tiny problem. I wanna put an actionlistener into a JTextField, so it printout something whenever a key is pressed (when the textField is selected).
I can only get it to print if I assign a specific key to pressed...example below (works):
JTextField searchBox = new JTextField();
InputMap imap = searchBox.getInputMap();
ActionMap amap = searchBox.getActionMap();
imap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "pressed");
amap.put("pressed", new AbstractAction() {
          public void actionPerformed(ActionEvent e) {
               System.out.println("TYPEEEEEEEEEEEEEEE");
HOWEVER, when i change keystroke to any key pressed, it doesn't work. Example below(doesn't work):
JTextField searchBox = new JTextField();
InputMap imap = searchBox.getInputMap();
ActionMap amap = searchBox.getActionMap();
imap.put(KeyStroke.getKeyStroke(KeyEvent.KEY_PRESSED, 0), "pressed");
amap.put("pressed", new AbstractAction() {
          public void actionPerformed(ActionEvent e) {
               System.out.println("TYPEEEEEEEEEEEEEEE");
Somebody plz helps me. I am really confused how to use KeyEvent.KEY_PRESSED. I thought it would work the same way as KeyEvent.VK_A...if i can't use KEY_PRESSED for that purpose, what KeyEvent do I use?
Thank you very much in advance.

Sounds like you want a KeyListener.
textField.addKeyListener(new KeyListener() {
    public void keyTyped(KeyEvent e) {
        System.out.println("Key typed.");
    public void keyPressed(KeyEvent e) {
        System.out.println("Key pressed.");
    public void keyReleased(KeyEvent e) {
        System.out.println("Key released.");
});See the API documentation for more information.

Similar Messages

  • How to detect any key pressed for program running in the background?

    Hi All,
    is it possible to detect when any key is pressed if a java program is not in the focus? For example, when I have a console based program I can write something like:
    System.in.read();
    and wait until any key is pressed. However, if I move the mouse away from the console and make any other window active, the console program "doesn't hear" anything. Ok, it's clear, of course, but how is it possible to make the program detect any keys pressed even if it's running in the background?
    Thanks a lot for any hints!

    qnx wrote:
    1) Stop trying to make spyware. -> I don't do anything like this!
    2) Stop re-posting the same questions. -> didn't know they are the same, sorry.
    3) Stop taking us for fools. -> what? Honestly, I don't think that I realy deserved this :)With a limited posting history and the type of questions you are asking they are unusual.
    There are very few legitimate problem domains that would require what you are asking about. There are illegitimate ones though. And the legitimate ones would generally require someone with quite a bit of programming experience and would also be required (the fact that java can't do it would not get rid of the requirement.)
    Thus one might make assumptions about your intentions.

  • HOW to use InputMap and ActionMap for a JButton ?

    Hi,
    I used to call the registredKeyBoardAction to deal with JButton keyBoard actions.
    It is written in the JavaDoc that this method is deprecated, so I try to use the InputMap and ActionMap as described in this doc without success.
    Does anybody has a piece of code that uses
    jButton.getInputMap().put(aKeyStroke, aCommand);
    jButton.getActionMap().put(aCommmand, anAction);
    for the space keyboard key, calling the "foo" actionCommand ?
    Thanks.

    To be more clear, from the API it seems as if you can set an Action for a keystroke. That is only for the component that you set the keystroke for. So if you set it for a button then it would seem that if it does automatically listen for keystrokes it would only do so when that button has focus. try setting the ActionMap for the window.

  • Using InputMap and ActionMap

    Referring to an earlier post "Listening to Keystrokes", I already know how to
    trap keystrokes in a JPanel. I use this line of code:
    this.registerKeyboardAction(this,
          "Exit Task", KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
          JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);[/cpde]
    However, the documentation for registerKeyboardAction() states:
    This method is now obsolete, please use a combination of getActionMap() and
    getInputMap() for similiar behavior. For example, to bind the KeyStroke
    aKeyStroke to the Action anAction now use:
       component.getInputMap().put(aKeyStroke, aCommand);
    component.getActionMap().put(aCommmand, anAction);
    Therefore, I attempt to use the getInputMap() and getActionMap() method. Since the documentation for registerKeyboardAction is:public void registerKeyboardAction(ActionListener anAction,
                                       String aCommand,
                                       KeyStroke aKeyStroke,
                                       int aCondition)I thought inside the JPanel, I only have to add these lines:
    this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "Exit Task");
    this.getActionMap().put("Exit Task", this);Unfortunately, the second line will give compilation errors. Note that the JPanel already implements ActionListener. So I check the documentation for ActionMap and realise that the put() method has two parameters, Object key and Action anAction. It seems that I have to this (a JPanel class) to Action. I thought casting should work since ActionListener is a superinterface to Action, but when I run the program, it will throw a ClassCastException.
    Therefore, I ended up implementing ActionListener AND Action. I also have to implement two abstract methods from Action.
    Did I miss anything? Does the JPanel really need to implement Action? Why can't I cast an ActionListener class to Action?
    Finally, is there a more elegant solution?
    Thank you in advance.

    Hi,
    Hi Shannon,
    Another problem... When we use
    registerKeyboardAction() for a toolbar button, its
    tool tip displays the key stroke used along with any
    text you may have set as the tool tip. So if I have
    JButton oBtn = new JButton();
    oBtn.setIcon(new ImageIcon("SomeIcon.gif"));
    oBtn.setToolTipText("Button Tool Tip");
    oBtn.registerKeyboardAction(handler, null,
    KeyStroke.getKeyStroke(KeyEvent.VK_N,
    InputEvent.CTRL_MASK,
    true),
    JComponent.WHEN_IN_FOCUSED_WINDOW);when I try to view the tool tip, I actually see
    "Button Tool Tip Ctrl-N" with the 'Ctrl-N' in a
    different font and color than the remaining text. But
    when I use the getActionMap() and getInputMap()
    methods, this extra information is not seen in the
    tool tip.Actually, even using getActionMap() and getInputMap(), you will see the control text. For example, the following is the equivalent of your code using getActionMap() and getInputMap():
    oBtn.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
            KeyStroke.getKeyStroke(KeyEvent.VK_N,
            InputEvent.CTRL_MASK,
            true), "handler");
    oBtn.getActionMap().put("handler", new AbstractAction(.....));As you'll see, it also shows the Ctrl-N in the tooltip text.
    Since this behavior has been around since the very early days of Swing, I cannot give you the exact reason for it. However, I suspect it was assumed at the time that if a keystroke is added to a component for WHEN_IN_FOCUSED_WINDOW, then that keystroke is one that will activate the component.
    Now, can I ask why you're adding this keyboard action to the button? Since its WHEN_IN_FOCUSED_WINDOW, you could add it to the contentpane or the rootpane. It doesn't need to be on the button.
    Any help in this case??? My team leader
    would prefer a function that is said to be outdated
    but works so much better, rather than some new fangled
    technique that doesn't give the same help....Just so you know, here's the implementation of registerKeyboardAction:
    public void registerKeyboardAction(ActionListener anAction,
                                       String aCommand,
                                       KeyStroke aKeyStroke,
                                       int aCondition) {
        InputMap inputMap = getInputMap(aCondition, true);
        if (inputMap != null) {
            ActionMap actionMap = getActionMap(true);
            ActionStandin action = new ActionStandin(anAction, aCommand);
            inputMap.put(aKeyStroke, action);
                if (actionMap != null) {
                    actionMap.put(action, action);
        }What am I trying to say? That the old technique simply uses the new technique internally. And it creates an action per keystroke. You might want to reconsider moving over to the new technique. I'd be happy to address any concerns you might have.
    Thanks,
    Shannon Hickey (Swing Team)
    >
    PLEASE HELP!!!
    Regards,
    Shefali

  • InPutMap and actionMap

    Hello.
    I am currently working on a larger project, where I'd like to make certain JButtons respond to the pressing of certain keys.
    To make this simpler, I wrote a smaller program with only one button, just to make the code easier to read.
    I've been working with Java for about 8 months now, and still do consider myself a novice, so any help I can get is greatly appreciated.
    In the posted example, I have a JButton that changes the text of a JTextField when pressed, however, I'd like to make the button respond when I press "a" on my keyboard,
    and for this I should use keybindinds (as far as I've understood). I've tried using inPutMap and actionMap, but haven't had any luck making them work yet.
    I added comments in the code, that shows where I'm in doubt. Again, any help is greatly appreciated, and I did read the tutorial at
    [http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]
    /* The imports */
    import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
    public class inPutExample extends JFrame implements ActionListener {
        /* Initialization */
        private JButton actionButton;
        private JTextField textField;
        /* My main method */
        public static void main (String[] Args) {
            inPutExample frame = new inPutExample();
            frame.setSize(200,120);
            frame.createGUI();
            frame.setVisible(true);
        /* The interface */
        private void createGUI() {
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            Container window = getContentPane();
            window.setLayout(new FlowLayout());
            /* My button, that needs to respond to a keypress */
            actionButton = new JButton("Press me");
            window.add(actionButton);
            actionButton.addActionListener(this);
            /* The inPutMap for my button.
             In the tutorial, they didn't use
             keyEvent, but simply wrote a letter in quotation marks,
             so I'm a bit confused on that */
            actionButton.getInputMap(JButton.WHEN_IN_FOCUSED_WINDOW)
                    .put(KeyStroke.getKeyStroke("a"), actionButton);
            /* The actionMap for my button. I'm confused
             as to what to put after the comma */
            actionButton.getActionMap().put(actionButton, null);
            /* The textfield that allows me to see
             if the button has been pressed */
            textField = new JTextField("Button hasn't been pressed");
            window.add(textField);
        public void actionPerformed(ActionEvent e) {
            Object source = e.getSource();
            /* The action that is performed
             when the button is pressed */
            if (source == actionButton) {
                textField.setText("Button has been pressed");
    }Any help or constructive criticism will be appreciated and responded to.
    Ulverbeast

    Compare you code again to the tutorial:
    component.getInputMap().put(KeyStroke.getKeyStroke("F2"),
                                "doSomething");
    component.getActionMap().put("doSomething",
                                 anAction);
    //where anAction is a javax.swing.ActionAlthough using the action button as action command (the 'doSomthing') works, that isn't really a good idea - stick with Strings. The crucial thing missing in the actual action though:
    Action action = new AbstractAction("Press me") {
      public void actionPerformed(ActionEvent e) {
        textField.setText("Button has been pressed");
    button = new JButton(action);
    // and put button in action map

  • The Control A key is not working. I cannot multi-select my songs. I'm not sure if it is the problem with iTunes 10.6.1.7 or my PC settings encounter issues. Also, i cannot find Album Artwork online using iTunes and i cannot select any view form but List.

    The Control A key is not working. I cannot multi-select my songs. I'm not sure if it is the problem with iTunes 10.6.1.7 or my PC settings encounter issues. Also, i cannot find Album Artwork online using iTunes and i cannot select any view form but List.

    The Control A key is not working. I cannot multi-select my songs. I'm not sure if it is the problem with iTunes 10.6.1.7 or my PC settings encounter issues. Also, i cannot find Album Artwork online using iTunes and i cannot select any view form but List.

  • My iphone 4s is no longer detecting wifi since the ISO8 updates came out. I've restarted, rest the networks, reset the phone back to factory settings, and even tried the freezer trick. It is STILL not detecting ANY wifi networks. HELP!!!

    My iphone 4s is no longer detecting wifi since the IOS8 updates came out. I've restarted, rest the networks, reset the phone back to factory settings, and even tried the freezer trick. It is STILL not detecting ANY wifi networks. HELP!!! I cannot afford to go over my data and I use wifi at home and work... I believe the updates have caused the issue, because it was working fine before the second update released (I hadn't put the first one one until I noticed it had stopped working, and by then the second IOS8 version had came out). They need to do a third update to fix this issue.

    If it's grayed out:
    Reset Network Settings - if that doesn't fix it, then Backup and Restore AS A NEW DEVICE.
    If it's still grayed out, unfortunately that means your Wi-Fi antenna quit, and it needs service.

  • So when I try to update or download an app it says I don't have enough storage. I don't know how to use iCloud and stuff soo what do I do? Help! I don't wanna delete any pics either.

    So when I try to update or download an app it says I don't have enough storage. I don't know how to use iCloud and stuff soo what do I do? Help! I don't wanna delete any pics either.

    JUst experienced the exact  same problem after changing password.Getting same message. Hope someone has an answer for this.

  • I want to detect a key press

    To detect a key press, i know i have to use the keylistener class
    public class key implements KeyListener{
         public static void main (String args[]){
              addKeyListener(this);
              keyReleased(KeyEvent e) {}
              keyTyped(KeyEvent e) {}
              keyPressed(KeyEvent e) {
    I built a simple program but it doesn't compile, it has an error.
    All i want is to detect a key press and do something for key presses...
    What am i doing wrong?

    I once got the following demo file somewhere in the Sun/Java site, probably in one of the link cited above..
    * Swing version
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    public class KeyEventDemo extends JApplet
                              implements KeyListener,
                                         ActionListener {
        JTextArea displayArea;
        JTextField typingArea;
        static final String newline = System.getProperty("line.separator");
        public void init() {
            JButton button = new JButton("Clear");
            button.addActionListener(this);
            typingArea = new JTextField(20);
            typingArea.addKeyListener(this);
            displayArea = new JTextArea();
            displayArea.setEditable(false);
            JScrollPane scrollPane = new JScrollPane(displayArea);
            scrollPane.setPreferredSize(new Dimension(375, 125));
            JPanel contentPane = new JPanel();
            contentPane.setLayout(new BorderLayout());
            contentPane.add(typingArea, BorderLayout.NORTH);
            contentPane.add(scrollPane, BorderLayout.CENTER);
            contentPane.add(button, BorderLayout.SOUTH);
            setContentPane(contentPane);
        /** Handle the key typed event from the text field. */
        public void keyTyped(KeyEvent e) {
            displayInfo(e, "KEY TYPED: ");
        /** Handle the key pressed event from the text field. */
        public void keyPressed(KeyEvent e) {
            displayInfo(e, "KEY PRESSED: ");
        /** Handle the key released event from the text field. */
        public void keyReleased(KeyEvent e) {
            displayInfo(e, "KEY RELEASED: ");
        /** Handle the button click. */
        public void actionPerformed(ActionEvent e) {
            //Clear the text components.
            displayArea.setText("");
            typingArea.setText("");
            //Return the focus to the typing area.
            typingArea.requestFocus();
         * We have to jump through some hoops to avoid
         * trying to print non-printing characters
         * such as Shift.  (Not only do they not print,
         * but if you put them in a String, the characters
         * afterward won't show up in the text area.)
        protected void displayInfo(KeyEvent e, String s){
            String charString, keyCodeString, modString, tmpString;
            char c = e.getKeyChar();
            int keyCode = e.getKeyCode();
            int modifiers = e.getModifiers();
            if (Character.isISOControl(c)) {
                charString = "key character = "
                           + "(an unprintable control character)";
            } else {
                charString = "key character = '"
                           + c + "'";
            keyCodeString = "key code = " + keyCode
                            + " ("
                            + KeyEvent.getKeyText(keyCode)
                            + ")";
            modString = "modifiers = " + modifiers;
            tmpString = KeyEvent.getKeyModifiersText(modifiers);
            if (tmpString.length() > 0) {
                modString += " (" + tmpString + ")";
            } else {
                modString += " (no modifiers)";
            displayArea.append(s + newline
                               + "    " + charString + newline
                               + "    " + keyCodeString + newline
                               + "    " + modString + newline);
    }

  • I have a scenario. Import IDOC into PI and PI transform IDOC to Excel. Using mail adapter attach that Excel using pi and send to customer. Can you please help me on the same?

    HI Experts,
    I have a scenario. Import IDOC into PI and PI transform IDOC to Excel. Using mail adapter attach that Excel using pi and send to vendor. Can you please help me on the same?
    Thanks
    SaiSreevastav

    Hi Sai,
    you can use XSLT or java mapping or adapter module to convert IDOC xml to XLS. Please refer the below blog
    Convert incoming XML to Excel or Excel XML – Part 1 - XSLT Way
    Convert incoming XML to Excel Sheet Part 2 – Adapter Module way
    Convert incoming XML to Excel Sheet
    then after converting to Excel, you can use the payloadswap bean in mail adapter
    XI: Sender mail adapter - PayloadSwapBean - Step by step
    regards,
    Harish

  • Is there any official market or store or anything in Egypt to fix my iphone 4 it jumped from 5th floor and the back hous was crashed and the network sensor was not working good but the phone and the screen and the others things are ok so plz help ???

    Is there any official market or store or anything in Egypt to fix my iphone 4 it jumped from 5th floor and the back hous was crashed and the network sensor was not working good but the phone and the screen and the others things are ok so plz help ???
    my iphone is now just coverd with case and the back house is crased

    Etisalat, Mobinil and Vodafone provide warranty service in your country.  You can also search Google for a 3rd party repair shop near you.

  • Can you explain when using keywords and addding them to various clips pressing ctrl and a number eg. 1 or 2 it simply closes down FCPX.  Just to the dock as would th yellow -sign. As you gather I am new to this program having only used Final Cut Express 4

    Can you explain when using keywords and addding them to various clips pressing ctrl and a number eg. 1 or 2 it simply closes down FCPX.  Just to the dock as would the yellow -sign.  I am new to this program having only used Final Cut Express 4 previously.
    iMac (early 2009) 24in 2.93GHz 4GB 1066MHz DDR3 SDRAM (To be upgraded ot 8GB in the nextfew days) os x 10.7.2 Lion
    Re: Why don't my arrows on the time line operate and allow me to move to the start and end of the timeline. Iam using the trial version 

    Check System Preferences. I think Control-1 is used by something in the OS now. Switch it off. It's a major p[ain the way the OS is taking over more and more of the keyboard, allowing less options for application use.

  • Have problems with Mail on MacBook running OS X Mavericks. It suddenly became stuck: won't quit and won't display any messages. Please help.

    Have problems with Mail on MacBook running OS X Mavericks. It suddenly became stuck: won't quit and won't display any messages. Please help.

    Select Force Quit from under the Apple menu and select Mail (it may say that it isn't responding).
    Clinton

  • Ive restored my ipod touch and updated everthing but whenever i plug it in the computer it freezes and i cannot sync any songs. can anyone help?

    ive restored my ipod touch and updated everthing but whenever i plug it in the computer it freezes and i cannot sync any songs. can anyone help?

    Did you happen to install Cydia or what they refer to as jailbreaker recently?

  • Detecting two keys press at one time

    i need to do a event handler, say when user press shift + enter, it will do something, else enter would do another thing
    i tried but i can't get the event handler to detect two key press, how do I go about it?

    VK_ENTER vs (VK_ENTER + SHIFT_DOWN_MASK)

Maybe you are looking for