HOW to use InputMap and ActionMap for a JButton ?

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 ?

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.

Similar Messages

  • 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:
          "Exit Task", KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
    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 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,
    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():
            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.
    Shannon Hickey (Swing Team)

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

    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) {
    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) {
    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.

  • How to use Find and Replace for CR or TAB

    How can I use PAGES 'Find and Replace' function to eliminate unwanted carriage returns or Tabs?
    I tried to copy the backwards P and paste into Pages find window, but that doesn't work.
    eMac   Mac OS X (10.4.4)   1 G RAM

    Copying & pasting should work, but it isn't necessary. In the Find & Replace fields hold down the Option key & hit the return or tab key.

  • How to use getCustomizing and setCustoming for charts?

    Hi. Experts!
    Can you give examples for using setCustomizing method for charts?
    And i'm have problem with multi-byte language in the chart caption.
    It's shown normally in the desinger, but not after deploying.
    If i'm open component source (chart node) (don't remember file extension)
    i'm see what problem occured here
    <?xml ..... utf-8>
    <! CDATA .........<?xml ......utf-8>
    <Caption>Chart Caption here</Caption
    P.S. NWDS 7.0.15


  • How to use servlets and JSP for my homepage?

    servlets and JSP are server-side program. If my homepage is on some web-hosting websites, can I upload the servlets and JSP to run it? if possible, where can I find such a web-hosting place?

    Not many hosts offer JSP or Servlet support (and some do but then stop and never give you a refund, grrrrrrr!!!!).
    Also, ones that do support it can often be more expensive. There are some free ones but all the one's I've come across have problems that made them unsuitable for my needs.
    Here is a list of hosts that support Java:
    I can't comment on any from that list, however I use they are a bit pricey but they have excellent support and are always happy to help with any Tomcat (the JSP/Servlet server they use)configuration issues or needs that you may have.

  • InPutMap and actionMap

    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
    /* 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();
        /* The interface */
        private void createGUI() {
            Container window = getContentPane();
            window.setLayout(new FlowLayout());
            /* My button, that needs to respond to a keypress */
            actionButton = new JButton("Press me");
            /* 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 */
                    .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");
        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.

    Compare you code again to the tutorial:
    //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

  • How to use protect and protect

    how to use protect and endprotect for two different element.
    iam using one element for 'tax' and one for 'item total'
    i wnt to print two elements in one page only.

    What does 'Elements' mean for u?
    Text Elements?
    You can try to manage it in print program:
        COMMAND = 'PROTECT'.
        ELEMENT = 'ELEMENT1'.
        ELEMENT = 'ELEMENT2'.

  • How to Use the same iview for both KM End User and the KM Administrator

    Hi friends,
    *This is my scenario :* How to Use the same iview for both KM End User and the KM Administrator but with different Context
    Menu Options.
    i followed these steps but im getting same context menu for both KM End User and the KM Administrator .
    Assign the role Content Administrator to the user km_admin. This is needed so that km_admin can change
    the presentation settings for the KM Folder u201EReports_kmFolder‟.
    Now, login with user km_admin. Navigate to the Km Folder reports_kmFolder through Content Administration
    -> Km Content. Click on Details link of the folder reports_kmFolder.
    Go To Settings -> Presentation. Click on the tab u201ESettings for You‟-> Click on button u201ESelect Profile‟.
    Select the radio button corresponding to u201Elayout Set‟, and choose u201EConsumerExplorer‟ from the dropdown.
    Click u201EOK‟.
    Select both the check boxes corresponding to Items Affected as shown above, and click u201ESave‟
    Now, remove the u201ESuper Administrator‟ role from the user km_admin and login with this user.
    How rto resolve this????

    Hello Prasad,
    Most likely the user km_admin still has system principal roles assigned, even though you removed the Super Admin role, you should check that this user doesn't have any other admin roles, otherwise it will be considered a System Principal user and will therefore still have access to all content. For more information see
    Try creating a new user with just read access to the content and you should see that it will not be able to make any changes etc.

  • How to use multiple VCI strings for lap 1300 and 1200 (option 60) in one pool?

    Hi All,
    Hope to you a very happy new year,
    I have two differnt LAP 1300 and 1200 in my network and I need to add theme to the WLC,
    I successed to add one of theme by the option 60 in the DHCP pool at the Core SW,
    So my quetion is below:
    How to use multiple VCI strings for lap 1300 and 1200 (option 60) in one pool?
    Thanks in Advanced,

    To add to Scott's post.  Option 60 would be useful if you needed to put certain types of AP on specific controllers.  Otherwise, no real need to use it for the most part.
    Though, I do recall an issue a few years ago that some windows machines had issues getting DHCP if option 43 is being returned.
    Now, on an IOS switch, you can only configure one option 60 per DHCP scope
    Please remember to rate useful posts, and mark questions as answered

  • How to Use the language function for assignment and validation

    Hi All,
    If anyone can explain me in details with example ,how to use the language function for assignments and validations?

    Hi Arnab,
    The expression is checked only for the current MDM session.
    If u login with the ABC language it will always show the ABC language no matter how many times u execute it.
    Try connecting to the DM with the XYZ language.
    It should go to the if part rather than else.
    Hope it helps.

  • Hi yesterday i downloaded a software from i tunes for keyboard short cut and i don't know how to use them and install them, how to use keyboard shorts bought from i tunes

    hi yesterday i downloaded a software from i tunes for keyboard short cut and i don't know how to use them and install them, how to use keyboard shorts bought from i tunes

    You can install it on your iOS device (iPad, iPhone, iPod Touch) either by redownloading it directly on the device via the Purchased tab in the App Store app on it, or by connecting the device to your computer's iTunes and syncing it to it.
    Syncing apps from a Mac : iTunes 11 for Mac: Sync and organize iOS apps
    from a PC : iTunes 11 for Windows: Sync and organize iOS apps
    As to how to then use the app, if the description on the app's description page in the store doesn't describe how to use it in enough detail, then is there a link to the developer's website on its description page, and does that have details ?

  • How to find classtype and class for a material.

    How to find classtype and class for a material.
    which table contains this data.

    Hi Kiran,
    Check below sample code. Use this BAPI which will give all info about the class for the material.
      DATA:      l_objectkey_imp    TYPE bapi1003_key-object
                                         VALUE IS INITIAL.
      CONSTANTS: lc_objecttable_imp TYPE bapi1003_key-objecttable
                                         VALUE 'MARA',
                 lc_classtype_imp   TYPE bapi1003_key-classtype
                                         VALUE '001',
                 lc_freight_class   TYPE bapi1003_alloc_list-classnum
                                         VALUE 'FREIGHT_CLASS',
                 lc_e               TYPE bapiret2-type VALUE 'E',
                 lc_p(1)            TYPE c             VALUE 'P',
                 lc_m(1)            TYPE c             VALUE 'M'.
      SORT i_deliverydata BY vbeln posnr matnr.
      CLEAR wa_deliverydata.
      LOOP AT i_deliverydata INTO wa_deliverydata.
        REFRESH: i_alloclist[],
        CLEAR:   l_objectkey_imp.
        l_objectkey_imp = wa_deliverydata-matnr.
    *Get classes and characteristics
            objectkey_imp         = l_objectkey_imp
            objecttable_imp       = lc_objecttable_imp
            classtype_imp         = lc_classtype_imp
    *   READ_VALUATIONS       =
            keydate               = sy-datum
            language              = sy-langu
            alloclist             = i_alloclist
    *   ALLOCVALUESCHAR       =
    *   ALLOCVALUESCURR       =
    *   ALLOCVALUESNUM        =
            return                = i_return

  • How to use Add Query Criteria for the MySQL data Base in Netbeans ?

    How to use Add Query Criteria for the MySQL data Base in Netbeans Visual web pack.
    When the Query Criteria is add like
    SELECT ALL counselors.counselors_id, counselors.first_name, counselors.telephone,
    FROM counselors WHERE counselors.counselors_id = ?
    when i run this Query in the Query Window
    i get a error message Box saying
    Query Processing Error Parameter metadata not available for the given statement
    if i run the Query with out Query Criteria its working fine.

    *I am glad I am not the only one who have this problem. Part of issue has been described as above, there are something more in my case.
    Whenever I try to call ****_tabRowSet.setObject(1, userDropList.getSeleted()); I got error message as shown below:*
    The Java codes are:
    public void dropDown1_processValueChange(ValueChangeEvent event) {
    Object s = this.dropDown1.getSelected();
    try {
    this.User_tabDataProvider1.setCursorRow(this.User_tabDataProvider1.findFirst("User_Tab.User_ID", s));
    this.getSessionBean1().getTrip_tabRowSet1().setObject(1, s);
    } catch (Exception e) {
    this.log("Error: ", e);
    this.error("Error: Cannot select user"+e.getMessage());
    SQL statement for Trip_tabRowSet:
    SELECT ALL Trip_Tab.Trip_Date,
    FROM Trip_Tab
    WHERE Trip_Tab.User_ID = ?
    Error messages are shown below:
    phase(RENDER_RESPONSE 6,[email protected]) threw exception: com.sun.rave.web.ui.appbase.ApplicationException: java.sql.SQLException: No value specified for parameter 1 java.sql.SQLException: No value specified for parameter 1
    tandardWrapperValve[Faces Servlet]: Servlet.service() for servlet Faces Servlet threw exception
    java.sql.SQLException: No value specified for parameter 1
    at com.mysql.jdbc.SQLError.createSQLException(
    at com.mysql.jdbc.PreparedStatement.fillSendPacket(
    at com.mysql.jdbc.PreparedStatement.fillSendPacket(
    at com.mysql.jdbc.PreparedStatement.executeQuery(
    at com.sun.sql.rowset.internal.CachedRowSetXReader.readData(
    at com.sun.sql.rowset.CachedRowSetXImpl.execute(
    at com.sun.sql.rowset.CachedRowSetXImpl.execute(
    at com.sun.webui.jsf.component.TableRowGroup.getRowKeys(
    at com.sun.webui.jsf.component.TableRowGroup.getFilteredRowKeys(
    at com.sun.webui.jsf.component.TableRowGroup.getRowCount(
    at com.sun.webui.jsf.component.Table.getRowCount(
    at com.sun.webui.jsf.renderkit.html.TableRenderer.renderTitle(
    at com.sun.webui.jsf.renderkit.html.TableRenderer.encodeBegin(
    at javax.faces.component.UIComponentBase.encodeBegin(
    at com.sun.webui.jsf.component.Table.encodeBegin(
    at javax.faces.component.UIComponent.encodeAll(
    at javax.faces.component.UIComponent.encodeAll(
    at javax.faces.component.UIComponent.encodeAll(
    at javax.faces.component.UIComponent.encodeAll(
    at javax.faces.component.UIComponent.encodeAll(
    at javax.faces.component.UIComponent.encodeAll(
    at com.sun.faces.application.ViewHandlerImpl.doRenderView(
    at com.sun.faces.application.ViewHandlerImpl.renderView(
    at com.sun.rave.web.ui.appbase.faces.ViewHandlerImpl.renderView(
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(
    at com.sun.faces.lifecycle.LifecycleImpl.phase(
    at com.sun.faces.lifecycle.LifecycleImpl.render(
    at javax.faces.webapp.FacesServlet.service(
    at org.apache.catalina.core.ApplicationFilterChain.servletService(
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(
    at com.sun.webui.jsf.util.UploadFilter.doFilter(
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(
    at org.apache.catalina.core.StandardWrapperValve.invoke(
    at org.apache.catalina.core.StandardPipeline.doInvoke(
    at org.apache.catalina.core.StandardPipeline.invoke(
    at org.apache.catalina.core.StandardContextValve.invokeInternal(
    at org.apache.catalina.core.StandardContextValve.invoke(
    at org.apache.catalina.core.StandardPipeline.doInvoke(
    at com.sun.enterprise.web.WebPipeline.invoke(
    at org.apache.catalina.core.StandardHostValve.invoke(
    at org.apache.catalina.core.StandardPipeline.doInvoke(
    at com.sun.enterprise.web.VirtualServerPipeline.invoke(
    at org.apache.catalina.core.ContainerBase.invoke(
    at org.apache.catalina.core.StandardEngineValve.invoke(
    at org.apache.catalina.core.StandardPipeline.doInvoke(
    at org.apache.catalina.core.StandardPipeline.invoke(
    at org.apache.catalina.core.ContainerBase.invoke(
    at org.apache.coyote.tomcat5.CoyoteAdapter.service(
    at com.sun.enterprise.web.connector.grizzly.ProcessorTask.invokeAdapter(
    at com.sun.enterprise.web.connector.grizzly.ProcessorTask.processNonBlocked(
    at com.sun.enterprise.web.connector.grizzly.ProcessorTask.process(
    at com.sun.enterprise.web.connector.grizzly.ReadTask.executeProcessorTask(
    at com.sun.enterprise.web.connector.grizzly.ReadTask.doTask(
    Also when I tried to update my MYSQL connector / J driver to version 5.1.5 from 5.0.5 (NB 5.5.1) and 5.0.7 (NB 6.1), I could not get it work (looooong time to search some JDBC classes and with no response in the end) on both of my Netbean 5.5.1(on PC) and Netbean 6.1(on laptop) IDEs.
    Could anybody look into this issue.
    Many thanks
    Edited by: linqing on Nov 22, 2007 4:48 AM

  • How to use the second display for installation OS in my vertical lines iMac

    My 17" iMac display is full of vertical lines, it is unuseable. Does anyone know how to use the second display for Mac OS X or disable the first display for installation Mac OS x ?

    Go to: *System Preferences > Displays* and select the Arrangement tab, then relocate your Menu bar by dragging it to the other display.
    Unfortunately there is no Hardware or Software switch to turn off the iMac's Internal Display.

Maybe you are looking for

  • Date format in OBIEE 10g Calender Control

    Once date selected in Calender, it is taking Date-Time format automatically. i.e when we select 20/01/2013 in calender and select GO button, then it takes '20/01/2013 00:00:00'. How can we change from Date-Time format to Date format only. Best regard

  • PDF and Excel reports

    Hi Everyone, In Oracle BPM 11g, can we export to excel the worklist from inbox or from any other view from bpm workspace ? if not how can we provide export to excel functionality in bpm workspace . Thanks!.

  • Display word/pdf document in the HTML region or report

    Hi, How to display blob content stored in a table in HTML region or report region. I already have a process to display the image content. But my question here is how to display word/pdf document within the html region so that the user can read the do

  • E71 doesn't show caller's name

    Today I noticed that my E71 doesn't show any names when somebody calls me, neither does it show any names with text messages (SMS). It shows just the number.  It doesn't show any name, I tried it with 10+ different people, both calling and texting. 

  • Can we improve performence using usage tracking

    hi all wat is the use of usage tracking in obiee by using this can we improve report performance Thanks Sreedhar