javaswinggroovyjtableswingbuilder

Jtable requestFocusInWindow fails on second call


I have a Jtable setup with Groovy SwingBuilder, and I'm trying to keep an empty row in the table so users can continue to add new values. After the empty row (single column) is filled in, I immediately add a new row, edit the cell of that new row, and request focus on the table. During the first call to request focus, everything goes correctly (assume that I'm clicking on the cell first). After hitting enter to save my cell contents, I add another empty row and the request focus fails. Anyone have any suggestions on what might be going on?

SwingBuilder swingBuilder = new SwingBuilder()
JTable myTable = swingBuilder.table(autoCreateRowSorter: true, focusable: true)
table.myTable = swingBuilder.tableModel(list: [[value: "test"]) {
swingBuilder.closureColumn(header: "Values", 
  read: { row -> return row[value] }, 
  write: { row, newValue ->
    row[value] = newValue
    addNewRow(myTable)
  })
}

void addNewRow(JTable myTable) {
  List<Map<String, String>> myTableRows = myTable.model.getRows()
  if(myTableRows.findAll{ it[value].trim().isEmpty() }.size() == 0) { // prevent more than one empty row
    myTableRows.add([value: ""])
    myTable.model.fireTableDataChanged()

    // set focus on the newly created row
    int indexOfNewRow = myTable.convertRowIndexToView(myTableRows.findIndexOf { it[value] == "" })
    myTable.changeSelection(indexOfNewRow, 0, false, false)
    myTable.editCellAt(indexOfNewRow, 0)
    myTable.requestFocusInWindow() // succeeds on first call when I click this cell, fails on second when I hit enter after filling in a row
}

I have checked values for visible, displayable, and focusable, and all return true both times in this scenario. The one thing I did notice was when I overrode the input/action for the enter key on the table. After I initially click and edit, enter will save the row, create a new one, then focus on the new row. After I edit this new row and hit enter, nothing happens. Are two different objects in focus somehow?


Solution

  • The JTable needs to be declared with surrendersFocusOnKeystroke set to true. This allows for focus to be gained on any table editors for this JTable after a keyboard event (i.e. - me hitting the enter key from the previous edit).