Question

How do I ensure that only some of my columns in my JTable are selectable (meaning they route to my ListSelectionListener)?

I have added my listener as follows:

table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {...});
Was it helpful?

Solution

The simplest solution may be to create your own selection model:

table.getColumnModel().setSelectionModel(new DefaultListSelectionModel() {
    private boolean isSelectable(int index0, int index1) {
        // TODO: Decide if this column index is selectable
        return true;
    }

    @Override
    public void setSelectionInterval(int index0, int index1) {
        if(isSelectable(index0, index1)) {
            super.setSelectionInterval(index0, index1);
        }
    }

    @Override
    public void addSelectionInterval(int index0, int index1) {
        if(isSelectable(index0, index1)) {
            super.addSelectionInterval(index0, index1);
        }
    }
});

Note also that if you want to listen on column selection, you want to add your listener to the column model's selection model (not the table's selection model).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top