![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e942. Getting the Selected Cells in a JTable ComponentThe method for determining the selected cells depends on whether column, row, or cell selection is enabled.JTable table = new JTable(); if (table.getColumnSelectionAllowed() && !table.getRowSelectionAllowed()) { // Column selection is enabled // Get the indices of the selected columns int[] vColIndices = table.getSelectedColumns(); } else if (!table.getColumnSelectionAllowed() && table.getRowSelectionAllowed()) { // Row selection is enabled // Get the indices of the selected rows int[] rowIndices = table.getSelectedRows(); } else if (table.getCellSelectionEnabled()) { // Individual cell selection is enabled // In SINGLE_SELECTION mode, the selected cell can be retrieved using table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); int rowIndex = table.getSelectedRow(); int colIndex = table.getSelectedColumn(); // 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)) { // cell is selected } } } }
e940. Enabling Single or Multiple Selections in a JTable Component e941. Programmatically Making Selections in a JTable Component e943. Disabling Selections in a JTable Component e944. Getting the Anchor Cell in a JTable Component
© 2002 Addison-Wesley. |