this.tModel.insertRow(rowCount,new Object[] {"","","",""});
this.table.setRowSelectionAllowed(true);
this.table.changeSelection(0, 0, false, false);
this.table.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER) {
rowCount = this.table.getSelectedRow() + 1;
tModel.insertRow(rowCount,new Object[]{"", "","",""});
}
}
});
I am trying to create a jtable adding rows at run time on mouse click. i alredy added a default row. but i cant get selection on that row. and i want to change the selection to newly added row when added on the key pressed action?
please suggest an answer? thanks in advance
Firstly, I would encourage you to use the key bindings API, KeyListener
is a low level API and events can be consumed before you ever see them.
To change/set the row selection in a JTable
, you should use JTable#setRowSelectionInterval
InputMap im = getInputMap(WHEN_FOCUSED);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter");
ActionMap am = getActionMap();
am.put("enter", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
int rowCount = table.getSelectedRow() + 1;
tModel.insertRow(rowCount,new Object[]{"", "","",""});
table.setRowSelectionInterval(rowCount, rowCount);
}
});
To select the last entry in a table, you could use a method like this:
private void selectLastPossibleEntry() {
final int rowCount = tableModel.getRowCount();
final int selectedRowCount = jTable.getSelectedRowCount();
if (rowCount > 0 && selectedRowCount <= 1) // we do not want do destroy multiple selected lines by the user
jTable.setRowSelectionInterval(rowCount - 1, rowCount - 1);
}
or more general:
private void selectLastPossibleEntryForJTable(final JTable jTable) {
final int rowCount = jTable.getModel().getRowCount();
final int selectedRowCount = jTable.getSelectedRowCount();
if (rowCount > 0 && selectedRowCount <= 1) // we do not want do destroy multiple selected lines by the user
jTable.setRowSelectionInterval(rowCount - 1, rowCount - 1);
}
Hint: This does not take care of different sortings