Question

public boolean searchSummaryData(String textToFind) {
int fromRow, fromCol;

fromRow = summaryTable.getSelectedRow();
fromCol = summaryTable.getSelectedColumn();

if (fromRow < 0) {
    fromRow = 0; //set to start point, first row 
}
if (fromCol < 0) {
    fromCol = 0;
} else if (fromCol == lastFoundCol) {
    fromCol++;
}
int searchIteration = 1;

if (fromRow != 0 || fromCol != 0) {
    searchIteration = 2;
}
for (int iterate = 1; iterate <= searchIteration; iterate++) {
    for (int i = fromRow; i < summaryTableModel.getRowCount(); i++) {
        for (int j = fromCol; j < summaryTableModel.getColumnCount(); j++) {
            final Object valueAt = summaryTableModel.getValueAt(i, j); //point to object at i,j
            if (valueAt != null) {
                textToFind = textToFind.toLowerCase();
                if (valueAt.toString().toLowerCase().contains(textToFind)) {
                    //Map the index of the column/row in the table model at j/i to the index of the column/row in the view.
                    int convertRowIndexToView = summaryTable.convertRowIndexToView(i);
                    int convertColIndexToView = summaryTable.convertColumnIndexToView(j);
                    summaryTable.setRowSelectionInterval(i, i);
                    summaryTable.setColumnSelectionInterval(j, j);
                    //Return a rectangle for the cell that lies at the intersection of row and column.
                    Rectangle rectToScrollTo = summaryTable.getCellRect(convertRowIndexToView, convertColIndexToView, true);
                    tableSp.getViewport().scrollRectToVisible(rectToScrollTo);
                    lastFoundCol = j;
                    return true;
                }
            }
        }
        fromCol = 0;
    }
    fromRow = fromCol = 0;
}
return false;

What is the psuedo code for the above method? I'm struggling to understand the state changes. It is supposed to do an incremental search on JTable of the text supplied as Parameter for this method.

Was it helpful?

Solution

// if the selection is (0, 0) prepare to skip the second search

// for each cell starting at the selection (first search)
    // get the value
    // if it exists and matches the search string
        // select that cell and scroll to show it
        // mark cell as last found
        // return true to show you found something
// if nothing was found, repeat the above starting from (0,0)

// if still nothing found, return false to say the desired string is not present.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top