简体   繁体   中英

focus next cellEditor and sellect all text in it in JTable when press enter key

I want the enter key to act like tab key on JTable. I know that this problem has been asked a few time already, and i used a solution found in this page : Use Enter Key Act Like Tab Key on jTable .

    KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
    KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
    InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    im.put(enter, im.get(tab));

and the solution work like a charm. but when using tab key, I've overridden the changeSelection of JTable,and override getTableCellEditorComponent of the cell editor to selectAll text in the textField in the next cell :

in JTable

   @Override
   public void changeSelection(int row, int column, boolean toggle, boolean extend) {
       super.changeSelection(row, column, toggle, extend);

       if (editCellAt(row, column)) {
           Component editor = getEditorComponent();
           editor.requestFocusInWindow();
       }
   }

an in CellEditor

    @Override
    public Component getTableCellEditorComponent(JTable table,
            Object value, boolean isSelected, int row, int column) {

           if (isSelected ) {
                SwingUtilities.invokeLater(new Runnable() {

                 @Override
                 public void run() {
                     textField.selectAll();
                 }
                });
          }
          return super.getTableCellEditorComponent(
                table, value, isSelected, row, column);
    }

so when i stroke the tab key the next cell is focused and the text in it is sellected, but when i type the enter key the first time the cell loose focus, and the second enter the next cell gain focus and the text in it is selected.

so my question is: Is there a way so the first enter loose focus from the cell and gain the focus for the next one (so it will act exactly like the tab key)

Don't know if it will make a difference but I've just overridden the changeSelection(...) method to do the cell selection:

if (editCellAt(row, column))
{
    Component editor = getEditorComponent();
    editor.requestFocusInWindow();
    ((JTextComponent)editor).selectAll();
}

Post a SSCCE that demonstrates the problem if that doesn't help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM