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

Similar Messages

  • 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 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.

  • 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

  • Navigate JTable using Ctrl and arrow combination

    By default, one way to navigate cells in a JTable is by using the arrow keys. I need to change this so that the user must hold down the Ctrl key and then navigate with the arrows. The arrow keys alone will not have any cell navigation functionality... they will only be used for editing cells that contain a JTextField (or some variant).
    Can anyone help me with this? BTW...I am using jdk 1.4.1_03

    To answer my own question:
    Using the InputMap and ActionMap of the JTable, the keybindings can be removed or added, so for moving one column to the right by holding down CTRL and pressing the right arrow, it is as simple as:
    InputMap inputMap = table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    // KeyEvent.VK_RIGHT is the right arrow key, and 2 is the CTRL key mask
    inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 2), "selectNextColumn");Here are some links that were of help:
    http://java.sun.com/j2se/1.4.1/docs/api/javax/swing/doc-files/Key-Index.html
    http://javaalmanac.com/egs/javax.swing/ListKeyBinds.html?l=rel
    http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html

  • Uploading a file to server using ajax and struts

    My problem is i wrote a program to upload a file to the server using Ajax.
    Here iam used Struts and Ajax.
    The problem is when iam uploaded a file from my PC the file is uploading to the server in the upload folder located in the server my system.
    Iam using Tomcat server 5.0
    But when iam trying to access it through other system it is not doing so
    Giving an internal server error i,e 500.
    Iam putting the necessary documents for ur reference.
    Plz help me soon .
    My exact requirement is i have to upload a file to the upload folder located in the server.
    And i have to get the path of that file and display the file path exactly below the browse button from where iam uploaded a file.
    That should be done without page refresh and submit thats y iam used Ajax
    Any help would greatly appreciated
    Thanks and Regards
    Meerasaaheb.
    The action class is FilePathAction
    package actions;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    public class FilePathAction extends Action{
    public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    String contextPath1 = "";
    String uploadDirName="";
    String filepath="";
    System.out.println(contextPath1 );
    String inputfile = request.getParameter("filepath");
    uploadDirName = getServlet().getServletContext().getRealPath("/upload");
    File f=new File(inputfile);
    FileInputStream fis=null;
    FileOutputStream fo=null;
    File f1=new File(uploadDirName+"/"+f.getName());
    fis=new FileInputStream(f);
    fo=new FileOutputStream(f1);
    try
    byte buf[] = new byte[1024*8]; /* declare a 8kB buffer */
    int len = -1;
    while((len = fis.read(buf)) != -1)
    fo.write(buf, 0, len);
    catch(Exception e)
    e.printStackTrace();
    filepath=f1.getAbsolutePath();
    request.setAttribute("filepath", filepath);
    return mapping.findForward("filepath");
    the input jsp is
    filename.jsp
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    <script type="text/javascript">
    alertflag = false;
    var xmlHttp;
    function startRequest()
    if(alertflag)
    alert("meera");
    xmlHttp=createXmlHttpRequest();
    var inputfile=document.getElementById("filepath").value;
    xmlHttp.open("POST","FilePathAction.do",true);
    xmlHttp.onreadystatechange=handleStateChange;
    xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlHttp.send("filepath="+inputfile);
    function createXmlHttpRequest()
    //For IE
    if(window.ActiveXObject)
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    //otherthan IE
    else if(window.XMLHttpRequest)
    xmlHttp=new XMLHttpRequest();
    return xmlHttp;
    //Next is the function that sets up the communication with the server.
    //This function also registers the callback handler, which is handleStateChange. Next is the code for the handler.
    function handleStateChange()
    var message=" ";
    if(xmlHttp.readyState==4)
    if(alertflag)
    alert(xmlHttp.status);
    if(xmlHttp.status==200)
    if(alertflag)
    alert("here");
    document.getElementById("div1").style.visibility = "visible";
    var results=xmlHttp.responseText;
    document.getElementById('div1').innerHTML = results;
    else
    alert("Error loading page"+xmlHttp.status+":"+xmlHttp.statusText);
    </script></head><body><form name="thumbs" enctype="multipart/form-data" method="post" action="">
    <input type="file" name="filepath" id="filepath" onchange="startRequest();"/>
    </form>
    <div id="div1" style="visibility:hidden;">
    </div></body></html>
    The ajax response is catching in a dummy.jsp
    <%=(String)request.getAttribute("filepath")%>
    corresponding action mapping
    <action path="/FilePathAction" type="actions.FilePathAction">
    <forward name="filepath" path="/dummy.jsp"/>
    </action>
    So plz help me to upload a file to the server from any PC.
    Iam searched alot but didnt get any solution.

    Plz help me soon if it possible so
    Iam in great need.
    I have worked alot but not worked out.
    Any help greatly appreciated

  • Using NULL and NOT NULL in prompted filters

    Dear all,
    While trying to grap the concept of prompted filters in sap bo web intelligence, I had a question whether why we cannot use NULL and NOT NULL while creating a prompted filters in our report.

    HI,
    'Is Null' and 'Not Null' are the predefined functions in webi which only eliminate the null values or considering only null values.
    'Is Null' and 'Not Null' are itself predefined functions that why you are not getting  prompts.
    Null values are standard across the databases so this is defined  as a function in webi to specific eliminate the null values.
    If something is not standard then there is option in the webi to use different operator with static values or with prompts.
    More more information on Null see the Null wiki page.
    Null (SQL) - Wikipedia, the free encyclopedia
    Amit

  • How do I use Qt and OpenGL with Visual Studio

    Hi! I mainly want to program in C++ and I want to use Qt and OpenGL with Visual Studio.
    I am currently revising C++ and later on i am going to start reading Qt and OpenGL. I have a background of
    Embedded firmware design(C and Assembly).
    The Visual Studio Version I have is 2013 ultimate. How do I use Qt and OpenGL with Visual Studio?
    Thanks
    Alexandros

    Hi ClassicalGuitar,
    The forum supports VS setup and installation. And your issue is not about the forum. I will move the thread to off-topic forum. Thanks for your understanding.
    Regards,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

  • Use VBA and Excel to open Dreamweaver HTML (CS5), find and replace text, save and close

    I wish to use VBA and Excel to programmatically open numbered Dreamweaver HTML (CS5) and find and replace text in the code view of these files, save and close them.
    I have  5000 associations between Find: x0001 and Replace: y0001 in an Excel sheet.
    I have the VBA written but do not know how to open, close and save the code view of the ####.html files. Please ... and thank you...
    [email protected]

    This is actually the code view of file ####.html that I wish to find and replace programmatically where #### is a four digit number cataloguing each painting.... In 1995 I thought this was clever... maybe not so clever now :>)) Thank you for whatever you can do Rob!
    !####.jpg!
    h2. "Name####"
    Oils on acrylic foundation commercial canvas - . xx X xx (inches) Started
    Back of the Painting In Progress </p> </body> </html>
    Warmest regards,
    Phil the Forecaster, http://philtheforecaster.blogspot.ca/ and http://phils-market.blogspot.ca/

  • How do I use the time capsule to share itunes music between multiple apple devices? Also, is it possible to control the music on one device using another, and how do you set this up?

    How do I use the time capsule to share itunes music between multiple apple devices? Also, is it possible to control the music on one device using another, and how do you set this up?

    unless i'm missing something, i think you got mixed up, this is easy google for walk throughs
    i'm assuming this is the new 3tb tc AC or 'tower' shape, if so, its wifi will run circles around your at&t device
    unplug the at&t box for a minute and plug it back in
    factory reset your tc - unplug it, hold down reset and keep holding while you plug it back in - only release reset when amber light flashes in 10-20s
    connect the tc to your at&t box via eth in the wan port, wait 1 minute, open airport utility look in 'other wifi devices' to setup the tc
    create a new wifi network (give it a different name than your at&t one) and put the tc in bridge mode (it may do this automatically for you, but you should double check) under the 'network' tab
    login to your at&t router and disable wifi on it
    add new clients to the new wifi network, and point your Macs to the time machine for backups

  • TS3999 I had an icloud account setup in 2009 when I first got my family members each a mac. I let that account expire(we never used it) and I don't know how to get it off of my ical. It is not recognizing any of the information to reset the password?

    I had an icloud account in 2009. We set it up as a family plan because my family had just changed from PC to Mac. We never used it and let the plan expire in 2010. My ical will not sync with my new iphone because it is linked to the family plan account that no longer exist. Because I don't remember my password, I tried resetting it. It says the personal information I entered is incorrect, but I know the information is correct...It's my birthday it asks for! Does anyone know how to get that account off of my mac without the account existing?

    You were a MobileMe (not iCloud) subscriber in 2009 and this service has been terminated. However the login is an Apple ID and this never expires. What is your operating system? Do you have a MobileMe icon in System Preferences? - if so you should be able to sign out in it, but you may not have an iCloud icon to let you create an iCloud account, though you can do so if your iPhone has iOS 5 or above.
    If you are getting login requests or other irritations from your MobileMe account you can go to (user)/Library/Preferences/ByHost and delete all .plist files beginning with com.apple.DotMac or com.apple.idisk, then reboot.
    The minimum requirement for iCloud to let you sync your data is 10.7.5 though you can sync through iTunes (except with Mavericks).

  • Can I use classes and methods for a maintenance view events?

    Hello experts,
    Instead of perform/form, can I instead use classes and methods, etc for a given maintenance view event, lets say for example I want to use event '01' which is before saving records in the database. Help would be greatly appreciated. Thanks a lot guys!

    Hi viraylab,
    1. The architecture provided by maintenance view
       for using EVENTS and our own code inside it -
       It is provided using FORM/PERFORM
       concept only.
    2. At this stage,we cannot use classes.
    3. However, inside the FORM routine,
       we can write what ever we want.
       We can aswell use any abap code, including
       classes and methods.
      (But this classes and methods won't have any
       effect on the EVENT provided by maintenance view)
    regards,
    amit m.

  • Error while accessing a library using content and structure

    I have a library having document and folder inside it. When I open the library using content and structure I get an error with a correlation ID. When checked the the logs with Correlation ID got an error message "View 'All Document' does not exist."
    'All Document' is name of default view on the library.
    When I open the library from view all site content the library is being opened.
    Please help!!!

    Hello Victoria,
    Thanks for  the response.
    I have tried troubleshooting steps given by you. 
    Check if the issue occurs with other users. Use another user to access the library in Content and Structure and then compare the results. --
    I tried with different users but no luck
    Make sure that the user account with issue has permission to view the All Documents view of the library. --
    Yes, user Account have the permission
    Check if the issue occurs with other libraries in the Content and Structure. If not, I recommend to save the library as
    a template including contents and then create a new library based on this template. After that use the new library instead of the old library. --
    No other library have this problem. I cannot save the library as template including the contents as the it has many folders and  files. The current size of library is 786 MB
    Clear cache in the browser or use another browser to see if the issue still occurs. --
    tries but issue persists.
    Best regards,
    Ratnesh

  • How do I install windows 7 on a macbook pro mid 2009 using bootcamp and no optical drive?

    How do I install windows 7 on a macbook pro mid 2009 using bootcamp and no optical drive?
    My optical drive is non-functional and I want to dual boot with win7. The only problem is my macbook does not boot from USB at all, even when I hold th ALT key down when it is starting up.
         -I have a flashdrive with win7 on it.
         -I mounted the ISO of win7 with toast for bootcamp to do its thing.

    Good luck.
    Consider this a bump so that hopefully someone with better news spots your thread.
    Allan

  • Using iPhoto and editing with Photoshop Elements 4

    Hello
    I am new to Macs after many years using PC and I am struggling to set up my photo workflow. I shoot in RAW format and input into iPhoto from iPhoto I double click on the photo and which opens the RAW editor in Photoshop Elements. After making changes I open the file in Photoshop and then save as a TIFF.
    My problem is I do not see the changed and saved file in iPhoto and if I double click on the photo again it opens back up in the RAW editor not as a TIFF.
    Can any one point me in the right direction to solve this or is what I am trying to do not possible
    Thanks
    Grant

    Grant
    Welcome to the Apple Discussions.
    What you're trying to do is not possible.
    When you save as a TIFF you create a whole new file that needs to be imported into iPhoto anew. iPhoto will track an edit as long as you stay with the same file - so, edit your jpeg in PSE and use the 'Save' command and the change is reflected in iPhoto. However, you cannot Save RAW files, it's always a Save As... and so the resulting file has to be imported.
    Regards
    TD

Maybe you are looking for