Escape Key Event in JTable

I have a KeyPressed event method in a java file where I am using the F3 and Escape keys. I have a JTable in the java file with values in it. The user can select any row in the table and when you press F3 or Escape key some methods get called up which deselect the chosen rows in the table. This works fine with the F3 key but when I put the exact same code in the Escape key event, nothing happens.
However when the focus goes off the JTable to another componement on the screen, pressing the Escape key now works. I want to have the Escape key working when the focus is on the table. Any suggestion please?

thanks for you response but I am still a bit confused. When I press the Esc key whilst the focus is on the JTable nothing happens but when the focus is off the JTable, all the methods in the Esc event get called and the rows in the table get deselected.
Is there any way of not having the JTable consuming the Esc key so the Esc key will work when focus is on the JTable.
I have a key pressed method registered to the class (not the JTable). Say that my class is called 'xinternetDesktop', my code is this:
public void xinternetDesktop_KeyPressed(java.awt.event.KeyEvent keyEvent) {
int code = keyEvent.getKeyCode();
switch (code) {
case KeyEvent.VK_ESCAPE : /*Escape key*/
resetListSelectionBidsAndOffers();
break;
case KeyEvent.VK_F3 : /*F3*/
resetListSelectionBidsAndOffers();
break;
Could u give any suggestion please.
Thank you

Similar Messages

  • Tricky Block Key Events in JTable

    Iam using a JTable . I donot want to use CustomTableModel to block the key events but I want to consume the keyevents as and when the user types in . In other words block the user from editing the cell but I donot want to make the cell un-editable . THis is a bit tricky I hope I have a solution for this

    Not sure exactly what you want but maybe this will give you some ideas:
    table = new JTable(model)
         protected void processKeyEvent(KeyEvent e)
              int column = table.getSelectedColumn();
              int row = table.getSelectedRow();
              if( row == ?? && column == ?? )
                   e.consume();
               else
                   super.processKeyEvent(e);
    };

  • Handling Enter key event in JTable

    Hi...
    This is particularly for the user "VIRAVAN"...
    I have followed your method ,and got results too.. but the
    processKeyBinding(.. method is called 4 times,same problem addressed by you before, but I didn't understood it...
    Please help me...
    Here is my code...
    protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,int condition, boolean pressed)
    System.out.println("Wait");
    if (ks == KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0))
    int selRow = getSelectedRow();
    int rowCount = getRowCount();
    int selCol = getSelectedColumn();
    String val =(String)getValueAt(selRow,selCol);
    boolean b= getCellEditor(selRow,selCol).stopCellEditing();
    System.out.println(b);
    System.out.println(rowCount-1 + " "+ selRow + " " + getSelectedColumn());
    if((!val.equals("")) && selRow==rowCount-1)
    System.out.println(rowCount-1 + " "+ getSelectedRow()+ " " + getSelectedColumn());
    blank1 = new String[columns];
    for(int p=0;p<columns;p++)
    blank1[p]="";
    Diary.this.datarows.addElement(blank1);
    // dataModel.fireTableStructureChanged();
    //dataModel.fireTableDataChanged();
    Diary.this.dataModel.fireTableChanged(null);
    else if(ks ==KeyStroke.getKeyStroke(KeyEvent.VK_1,0))
    System.out.println("One One One One ");
    return super.processKeyBinding(ks,e,condition,pressed);

    It's been a while since I looked at the code, but essentially there are three key event types:
    1) key pressed,
    2) key typed,
    3) key released.
    So I would expect the processKeyBind to see all three of them. However, ks==KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0) is true only when a key typed event is detected (the other types can be ignored by passing it up the food chain where they will eventually be consumed). Now...., if I understand you correctly, you want to terminate edit on the present of Enter key, right? Here is how I'd suggest you do:
       protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
          if (isEditing()) {
             Component editorComponent=getEditorComponent();
             editorComponent.stopCellEditing();
             return true;
          return super.processKeyBinding(ks,e,condition,pressed);
       }Ok.... now, it appears that you want to do something else also... i.e., add a new row to the table if the editing row is the last row and the editing column is the last column of the last row. You can't do that in the same thread (i.e., you must wait until the update in the current thread is completed). So, what you must do is use the SwingUtilities.InvokeLater, like this:
       protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
          if (isEditing()) {
             Component editorComponent=getEditorComponent();
             editorComponent.stopCellEditing();
             if (getEditingRow()+1==getRowCount() && getEditingColumn()+1==getColumnCount()) {
                SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
    // put the code for adding new row here
             return true;
          return super.processKeyBinding(ks,e,condition,pressed);
       }OK?
    ;o)
    V.V.
    PS: posted code is untest but should work!

  • Can't capture escape-key event

    I have made a class which implements KeyListener and have added to a dialog. The keyPressed(KeyEvent e) method is called with common keys but not with the escape-key. How can I make this work with the escape?

    This works for me:
    protected JRootPane createRootPane() {
        ActionListener escLis = new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                dispose();
        JRootPane rootPane = super.createRootPane();
        KeyStroke ks = KeyStroke.getKeyStroke (KeyEvent.VK_ESCAPE, 0);
        rootPane.registerKeyboardAction(escLis, ks, WHEN_IN_FOCUSED_WINDOW);
        return rootPane;
    }I'm pretty sure that registerKeyboardAction() has been deprecated so you'll probably want to replace that portion of the code.
    Col

  • Escape key in jtable while editing

    I am trying to unregister the escape key from the jtable when it is in an editing mode. The field in an editable mode is a JTextField. I tried:
    this.getInputMap().remove(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0));I also tried removing it from the JTextField in MyCellEditorObject (which extends DefaultCellEditor)
    But the escape key does not seem to be in either of these components when I do:
    KeyStroke[] ks = this.getInputMap().allKeys();
    if(null == ks)
        System.out.println("null ks........................");
    else
        for (int i = 0; i < ks.length; i++)
            System.out.println(ks.toString());
    Once I get this figured out I need to add and remove other keys to whatever object is handling the events.
    Does anyone know what object is handling the escape key in the JTable while it is in an editing state using a JTextField?

    Well, for others who may have the same problem this is what I found so far:
    The jtable.getInputMap() will always return null (hardcoded in BasicTableUI). To get the input map one has to put:
    jtable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
    Then
    KeyStroke[] ks = this.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).allKeys();
    returns keys in the input map and the parent input map....(.keys() will exclude the keys in the parent input map).
    For the JTable all the keys are registered in the parent inputMap.
    m_table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).getParent().remove(KeyStroke.getKeyStroke(KeyEvent.VK_ALPHANUMERIC, 0));
    m_tablegetInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).getParent().remove(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false));
    m_table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).getParent().put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true), "quitRelease");
    m_table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).getParent().put(KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0), "actionMApKeyObject");
    m_table.getActionMap().put("quitRelease", new QuitAction());
    m_table.getActionMap().put("send", new SendAction());
    private class QuitAction  extends AbstractAction
        public void actionPerformed(ActionEvent ae)
           //do quit cellediting stopped? yes then press quit btn no thenstop ...
    private class SendAction  extends AbstractAction
        public void actionPerformed(ActionEvent ae)
           //do send
    }I still would like to know more about the input maps...and the parent input map???
    As well as the ActionMaps all introduced in 1.3.
    Does anyone know of any URLs or books that contain good explanations and samples
    (I have not found any)...
    I am also interested in how this could be applied more globally
    like the enter key pressing all buttons in my application.
    Or having text fields respond to keyReleased rather than pressed.

  • Default behaviour of the Escape key while editing a cell in JTable??

    Hi all,
    i have a Jtable which get its data from an own model object which extends DefaultTableModel.
    If i overwrite the isCellEditable(row, col) method within the tablemodel object and set a specific column to editable, then i notice while editing a cell in that column that the default behaviour of the Escape key is that independet from what you have entered before in to the cell the editing stops and the cell gets the value it had before editing.
    This is the case for me even if i apply a custom editor to a column (one that extends DefaultCellEditor). It is just a JTextField that limits the number of digits a user can enter. Everything works fine. If the user edits the cell and presses ENTER or the "down arrow key" i can check what he has entered with the help of the getCellEditorValue() method. But if the user hits the ESC key after editing a cell this method is not invoked!!!
    My question is :
    is there any way to detect that the user cancels editing with the ESC-key.
    this is very important for me because if the user goes editing the cell i lock the related record in the database, if i cannot detect this it is locked till the application terminates.
    Thanks for any help in advance

    I try override the JTable editingCanceled() ==> does not work.
    I try the addCellEditorListener( CellEditorListener l ) ==> does not work.
    Finally, I try the addKeyListener ==> it works.
    Here is a quick demo. program:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class Test {
    public static void main(String[] args){
    JFrame f = new JFrame();
    String[] colName = {"a", "b"};
    String[][] rowData = {{"1", "2"}, {"3", "4"}};
    JTable table = new JTable(rowData, colName);
    JTextField t = new JTextField(10);
    t.setBackground(Color.red);
    t.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
    // do what ever you want ex. un-lock table
    System.out.println("ESCAPE");
    DefaultCellEditor editor = new DefaultCellEditor(t);
    TableColumnModel colModel = table.getColumnModel();
    for (int i = colModel.getColumnCount()-1; i >= 0; i--) {
    colModel.getColumn(i).setCellEditor(editor);
    f.setContentPane(new JScrollPane(table));
    f.pack();
    f.setVisible(true);

  • Escape key "dies" in combobox and JTable

    I have set in my JDialog the default key ESCAPE as this standard code:
              KeyStroke escKey = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
              int param = JComponent.WHEN_IN_FOCUSED_WINDOW;
              root.getInputMap(param).put(escKey, "close");
              root.getActionMap().put("close", actionCancel);
         this.btCancel.setAction(actionCancel);
    The problem is when I have JComboBoxs and JTables. All key events seem to be consumed
    In this components (and maybe more components). So, if I press ESCAPE and my focus
    in a combobox, the dialog won't close.
    How could I work around this?
    thank you

    I've got the solution!
    I have a javaBean (JPanel) that has only one JComboBox. I trigger key pressed (don't know
    if should be key released in this case) on comboBox. Then I check if...
    this.comboBox.isPopupVisible().
    Simple. If popup is not visible and dispatch the event to this.
    I just wonder how the event goes to my javaBean, my javabean is in a dialog and this
    dialog of mine ends up to catch the event. ???
    Ok, this stays has a solution for future developers to found - in case they guess that
    right keywords :)

  • Handling keyTyped events in JTable for TAB key

    In my app, I have a JTable. Some columns are non-editable.
    I have attached a keyListener to the table and have overridden keyTyped() and keyReleased() methods.
    In keyReleased(), I do something depending on the key code. For example: if its the VK_DELETE, I delete the row. If its some other user configured key, then I show a popup dialog where the user can enter some data, etc...
    In keyTyped(), I first check if the column is one of the specific columns. Then I get the keyChar. After this, I show a dialog and pre-populate a JTextField on this dialog with that keyChar.
    My issue is that 'TAB' key events arrive in keyTyped() and not in keyReleased(). As a result, the dialog is shown and the tab takes place inside the JTextfield which is incorrect.
    I would like to ignore TAB keyTyped events. When I look up the keyCode in keyTyped() method, it is 0. So there is no way for me to tell what key was typed.
    How can I ignore TAB events in my keyTyped() method?
    thx

    I now do the following to determine if TAB key has been typed
    public void keyTyped(KeyEvent e) {
    char c = e.getKeyChar();
    if (c == KeyEvent.VK_TAB) {
    Is this correct ?
    Edited by: tsc on Sep 28, 2007 12:40 PM

  • Escape key no longer functioning to back out of photos in Event view

    In iPhoto '09, when you drilled down to view a photo in Event view, you used to be able to use the Escape key to step back a level. With iPhoto '11, I have been unable to do this. Is there a setting I'm missing or something?

    I just figured out a great solution to this problem! The goal here is to remap the Escape key in iPhoto so that it functions like the Command-Left-Arrow, which currently has all the functions we wish Escape had. The instruction are fairly simple:
    Install KeyRemap4MacBook. It's a wonderful program that lets you take control of your keyboard. It's stable and powerful and quick and free.
    Follow these instructions which tell you how to add your own custom settings. (Skip steps 4 through 6, which just give you some example settings to add.)
    Edit private.xml so that it looks like the following (or at least contains the following "item", if you have other custom settings installed):
    <?xml version="1.0"?>
    <root>
      <item>
        <name>Escape to Command Left Arrow</name>
        <identifier>private.app_iphoto_escape_to_command_left_arrow</identifier>
        <only>IPHOTO</only>
        <autogen>--KeyToKey-- KeyCode::ESCAPE, KeyCode::CURSOR_LEFT, ModifierFlag::COMMAND_R</autogen>
      </item>
    </root>
    Finally, save private.xml, then click "ReloadXML" under the "Change Key" tab of the KeyRemap4MacBook preferance pane. Your new setting should appear at the top of the list. Enable it. Restart iPhoto if you feel like it (you probably won't need to). And now, in iPhoto, Escape should work as you want it to!
    NOTE: There is one downside I've discovered. You won't be able to get out of Slideshow mode using the Escape key anymore, as this was the one case where Escape originally functioned sensibly. Rather, you'll have to use your mouse to click the X button to escape. But Slideshow mode is terrible anyway. Just use full screen mode instead.

  • How to handle form close event or escape key press event for user defined f

    Experts,
    Please let me know how to handle form close event or escape key press event for user defined form...
    Thanks & Regards,
    Pravin.

    Hi
    You can catch the form close event like this
    If ((pVal.FormType = 139 And (pVal.EventType = SAPbouiCOM.BoEventTypes.et_FORM_CLOSE)) And (pVal.Before_Action = True)) Then
          Try
                   SBO_Application.SetStatusBarMessage(pVal.EventType.ToString())
          Catch ex As Exception
                    SBO_Application.SetStatusBarMessage(ex.Message)
            End Try
          End If
    Hope this helps
    Regards
    Arun

  • Trapping key Event when DELETE is pressed in the JTAble

    I want to trap keyEvent when i press DELETE Key in the JTABLE.

    Hi,
    you could use InputMap and ActionMap, like below:
          // Read the maps
          InputMap inmap = yourTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
          ActionMap actmap = yourTable.getActionMap();
          // Build the action
          Action yourAction = new AbstractAction() {
             public void actionPerformed(ActionEvent e) {
                //... your event code here...
          // Map DELETE key to the action
          inmap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE), "Delete");
          actmap.put("Delete", yourAction);I didn't try this with a JTable, but it works perfectly with JList and JTree...
    Hope this will help,
    Regards.

  • 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

  • How to listen to key press in JTable

    I've been trying to listen to key press in JTable,
    However it only works if the cell is double-clicked.
    If the tab button is use or the cell is single-clicked, nothing happens to the listener.
    Anybody can help me???
    Thanks

    table.getColumnModel().addColumnModelListener(new TableColumnModelListener(){
      public void columnAdded(TableColumnModelEvent e){}
      public void columnMarginChanged(ChangeEvent e){}
      public void columnMoved(TableColumnModelEvent e){}
      public void columnRemoved(TableColumnModelEvent e){}
      public void columnSelectionChanged(ListSelectionEvent e){
        // column selection changed
    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
      public void valueChanged(ListSelectionEvent event) {
        // row selection changed
    });rykk

  • How can I get the escape key to work again?

    I've used "esc" to get out of VI's insert mode for 40 years. I am not going to relearn that keystroke as "ctl-esc", period. Even if I were to do that, then I'd be typing ctl-esc on other platforms where it would not work because I have to type "esc" alone. If there is a way to fix in in System Preferences->keyboard, I cannot find it. If there is not, then it is completely 100% brain-dead wrong. I hope that's not the case.  So there is definitely a bug:
    The key-up event on the escape key does not cause the escape key code to be delivered to the active window when no other key is pressed, or
    The UI is sufficiently obtuse that the cause of the suppression cannot readily be found.
    I do hope it is merely the latter because I am compelled to use Outlook and Outlook does not work properly under OS/X 10.6.  (Our Exchange Server is rigged to only allow Outlook clients to send email outside of the company.)
    Thank you.

    The answer is:  The bug is in the UI.  Speech recognition was enabled, by default it uses the bare escape key as a "mic on" indicator, and it does not leave any trace in the keybord configuration.  So that is the bug.  It needs to leave a trace there, a la: "X Listen-for-voice-command  ^" under Mission Control.

  • How do you identify a key events source (std keyboard or a USB barcode reader emulating keyboard)?

    I have attached a USB barcode reader which essentially emulates a USB
    keyboard. Having looked through the VC++ V5.0 documentation and some SDK
    documents that I have, I could not find a library function that identifies
    what device sourced the keyboad event.
    Does know if this is possible ? Anyone have any ideas ?
    Thanks.

    If you over ride the "CWnd:reTranslateMessage" function you'll be able to trap keyboard messages.
    ex:
    BOOL CTestexecDlg:reTranslateMessage(MSG* pMsg)
    if (pMsg->message == WM_KEYDOWN && (pMsg->wParam == 13 || pMsg->wParam == VK_ESCAPE))
    // Enter or escape key was pressed; return TRUE to stop default handling
    return TRUE;
    if (pMsg->message == WM_KEYDOWN && pMsg->wParam == 0x30)
    BringWindowToTop( );
    return TRUE;
    if (pMsg->message == WM_KEYDOWN && pMsg->wParam == 0x31 && m_DisplayObject1 != NULL)
    // Enter or escape key was pressed; return TRUE to stop default handling
    m_DisplayObject1->SetWindowToTop( );
    return TRUE;
    if (pMsg->message == WM_KEYDOWN && pMsg->wPa
    ram == 0x32 && m_DisplayObject2 != NULL)
    // Enter or escape key was pressed; return TRUE to stop default handling
    m_DisplayObject2->SetWindowToTop( );
    return TRUE;
    if (pMsg->message == WM_KEYDOWN && pMsg->wParam == 0x33 && m_DisplayObject2 != NULL)
    // Enter or escape key was pressed; return TRUE to stop default handling
    m_DisplayObject3->SetWindowToTop( );
    return TRUE;
    return CDialog:reTranslateMessage(pMsg);
    Steve

Maybe you are looking for