void (@NotNull JTable table) { int size = table.getModel().getRowCount(); if (size == 0) { table.clearSelection(); return; } int selectedIndex = table.getSelectedRow(); boolean reselect = false; if (selectedIndex < 0 || selectedIndex >= size) { // fit index to [0, size-1] range selectedIndex = 0; reselect = true; } ensureIndexIsVisible(table, selectedIndex, 0); if (reselect) { table.getSelectionModel().setSelectionInterval(selectedIndex, selectedIndex); } }