Mega Code Archive

 
Categories / Java Tutorial / Swing
 

Check each cell in the min and max ranges of selected cells

import javax.swing.JTable; import javax.swing.ListSelectionModel; public class Main {   public static void main(String[] argv) throws Exception {     JTable table = new JTable();     if (table.getCellSelectionEnabled()) {       // In the other modes, the set of selected cells can be retrieved using       table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);       table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);       // Get the min and max ranges of selected cells       int rowIndexStart = table.getSelectedRow();       int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();       int colIndexStart = table.getSelectedColumn();       int colIndexEnd = table.getColumnModel().getSelectionModel().getMaxSelectionIndex();       // Check each cell in the range       for (int r = rowIndexStart; r <= rowIndexEnd; r++) {         for (int c = colIndexStart; c <= colIndexEnd; c++) {           if (table.isCellSelected(r, c)) {             System.out.println("cell is selected");            }         }       }     }   } }