I want to transfer the cell focus to a particular cell in the JTable like when the focus on cell (2,3) and after pressing the enter key, focus should be transferred to the cell (2,5) that is skip one cell (2,4).
For this I am using a method changeSel开发者_运维问答ection() of JTable class but its not working.
Maybe you can find the answer in the place where cursor movement is done by the default UI implementation. jdk1.6.0_10\src\javax\swing\plaf\basic\BasicTableUI.java I assume it is the lead-selection index you're looking for.
Should focus be transferred only from that exact cell (2,3) or for all cells in column 3? In anyway here's an example that seems to do what you ask for. Though beware that this example take the following assumptions on the TableCellEditor:
- TableCellEditor should return the same component on each call to #getTableCellEditorComponent (since we add a KeyListener to it)
TableCellEditor may not fail when asked for a value not in table (if TableModel is empty during setup)
table.setSurrendersFocusOnKeystroke(true); table.getCellEditor(2, 3).getTableCellEditorComponent(table, null, false, 2, 3).addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER && table.getSelectedRow() == 2 && table.getSelectedColumn() == 3) { selectCell(2, 5); table.editCellAt(2, 5); focusEditedCell(); e.consume(); } } private void selectCell(int row, int col) { table.setRowSelectionInterval(row, row); table.setColumnSelectionInterval(col, col); } private void focusEditedCell() { Component c = table.getEditorComponent(); if (c != null) { c.requestFocusInWindow(); } } });
精彩评论