Search code examples
javaswingjframejtable

Set the view to a specific cell


Do you know how to set the view to a specific cell in a JTable? Because I'm working on searching for specific content in cells (Such Ctrl + F)

I have a specific cell such as row 39 and column 5, but I don't know how to view it

I have looked in JTable and DefaultTableModel but I don't see any useful methods.


Solution

  • If you want to Select (highlight) a specific JTable Cell then this could be one way you can do it:

    public static void selectJTableCell(javax.swing.JTable theTable, 
                             int literalCellRowNumber, int literalCellColumnNumber) {
        /* Set the Selection mode...   */
        theTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        /* Make sure ColumnSelectionAllowed is enabled 
          so that just the cell is selected.        */
        theTable.setColumnSelectionAllowed(true);
        /* Make sure RowSelectionAllowed is enabled. 
           (It should be by default anyways).     */
        theTable.setRowSelectionAllowed(true);
        /* Select the desired cell. We subtract 1 from 
           the supplied LITERAL Cell Row Number and the
           LITERAL Cell Column Number values supplied 
           since we're asking for the literal row/column
           numbers rather than index numbers. If you would 
           rather use an index value then remove the -1's.  */
        theTable.changeSelection(literalCellRowNumber - 1, literalCellColumnNumber - 1, false, false);
    }
    

    How you might use this method:

    selectJTableCell(jTable1, 39, 5);
    

    Consequently, if you want to select an entire JTable Row, then this could be one way you can do it:

    public static void selectJTableRow(javax.swing.JTable theTable, int literalRowNumber) {
        /* Subtract 1 from the supplied LITERAL Row 
           Number value supplied since we're asking 
           for the literal row number rather than the 
           index number. If you would rather use an 
           index value then remove this code line.  */
        literalRowNumber = literalRowNumber - 1;
        /* Disable ColumnSelectionAllowed otherwise the 
           row will not be highlighted.        */
        theTable.setColumnSelectionAllowed(false);
        /* Make RowSelectionAllowed is enabled.*/  
        theTable.setRowSelectionAllowed(true);
        /* Select the first cell in the desired row to 
           ensure the table will scroll to the row 
           selection so that it will be visible within 
           the viewport.                */
        theTable.changeSelection(literalRowNumber, 0, false, false);
        // Now, Select the row.
        theTable.setRowSelectionInterval(literalRowNumber, literalRowNumber);
        
    }
    

    How you might use this method:

    selectJTableRow(jTable1, 39);