eatSleepCode
eatSleepCode

Reputation: 4637

Keeping JTable selection

I am using JTable with MULTIPLE_INTERVAL_SELECTION when I call

 int[] selectedRows = jtable.getSelectedRows();

I am getting array of selected rows indexes like 5,6,8 for eg. Now In case of error I want to maintain same selection.

I am trying

_selectionModel.setSelectionInterval(selectedRows[0], selectedRows[selectedRows.length-1]);

but it is selecting rows from 5 to 8 how can I avoid to select row number 7 which wasn't selected before?

Upvotes: 1

Views: 102

Answers (1)

alex2410
alex2410

Reputation: 10994

For that purposes you can use addSelectionInterval() method instead of setSelectionInterval(). For example:

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class Example  {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JTable t = new JTable(10,1);
        frame.add(new JScrollPane(t));

        t.getSelectionModel().clearSelection();
        t.getSelectionModel().addSelectionInterval(5, 6);
        t.getSelectionModel().addSelectionInterval(8, 8);
        frame.pack();
        frame.setVisible(true);
    }

}

Upvotes: 3

Related Questions