Skip to content

A free, open-source alternative to Burp Suite: an intercepting proxy and web app security testing suite with Repeater, Intruder, Collaborator and a built-in OWASP ZAP scanner. Linux, AGPL-3.0.

1.6 KB
Raw Blame
package opensuite.ui;

import javax.swing.JTable;
import java.util.function.IntFunction;

/**
 * Tells a table's viewer when the selected item changes, and only then.
 *
 * <p>A sorted table that gains a row keeps its selection on the same item by
 * clearing the selection and making it again. Heard as two changes, that had
 * the viewer emptied and redrawn for every row added: hundreds of times a
 * second while a scan runs, which left the window no time to answer. Here the
 * item itself is compared, so a selection restored to the same item is not a
 * change at all.
 */
public final class RowSelection {
    private RowSelection() {}

    /**
     * @param itemAtModelRow the item a row of the table's model stands for, or null
     * @param changed        run when a different item, or none, becomes selected
     */
    public static void watch(JTable table, IntFunction<?> itemAtModelRow, Runnable changed) {
        Object[] last = {null};
        table.getSelectionModel().addListSelectionListener(e -> {
            int row = table.getSelectedRow();
            // Empty while a selection is still being made: the table restoring it, or a click not yet released.
            if (row < 0 && e.getValueIsAdjusting()) return;
            Object item = null;
            if (row >= 0) {
                try { item = itemAtModelRow.apply(table.convertRowIndexToModel(row)); }
                catch (IndexOutOfBoundsException gone) { return; }   // the row left the model as this was heard
            }
            if (item == last[0]) return;
            last[0] = item;
            changed.run();
        });
    }
}