1
 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,在运行时通过鼠标单击添加行。我已经添加了一个默认行。但我无法在该行上进行选择。我想在按键操作上添加时将选择更改为新添加的行?请提出答案?提前致谢

4

2 回答 2

3

首先,我鼓励您使用key bindings APIKeyListener这是一个低级 API,可以在您看到它们之前使用事件。

要更改/设置 a 中的行选择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);
    }
});
于 2012-10-30T10:55:08.217 回答
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);
}

提示:这不考虑不同的排序

于 2012-10-30T11:11:22.023 回答