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[]{"", "","",""});
}
}
});
我正在尝试创建一个jtable,在运行时通过鼠标单击添加行。我alredy添加了一个默认行。但我不能在那一行上做出选择。并且我想在按下键的操作上添加时将选择更改为新添加的行? 请建议一个答案?提前谢谢
答案 0 :(得分:3)
首先,我建议您使用key bindings API,KeyListener
是一个低级API,事件可以在您看到它们之前消费。
要更改/设置JTable
中的行选择,您应该使用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);
}
});
答案 1 :(得分:2)
要选择表格中的最后一个条目,您可以使用如下方法:
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);
}
或更一般:
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);
}
提示:这不会处理不同的排序