adding rows in jtable [closed]

ぃ、小莉子 提交于 2019-12-11 09:44:18

问题


 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


回答1:


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);
    }
});



回答2:


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



来源:https://stackoverflow.com/questions/13137091/adding-rows-in-jtable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!