Java Swing JTable selects multiple lines programmatically

I have a JTable with several rows, and each row is represented through a dot in a scatter chart. What I have to do is when the selected point is selected on the scatter chart, I have to associate this selection with the selection of the corresponding row in JTable.

I have an integer that represents which line I should select.

What I tried is this:

    JTable table = new JTable();
...
...// a bit of code where I have populated the table
...
   table.setRowSelectionInterval(index1,index2);

So the problem is that this method selects all rows in the given range [index1, index2]. I want to select, for example, lines 1,15,28,188, etc.

How do you do that?

+5
source share
4 answers

To select only one row, pass it as an index of the beginning and end:

table.setRowSelectionInterval(18, 18);

, :

ListSelectionModel model = table.getSelectionModel();
model.clearSelection();
model.addSelectionInterval(1, 1);
model.addSelectionInterval(18, 18);
model.addSelectionInterval(23, 23);

, ListSelectionModel , .

+11

ListSelectionModel:

table.clearSelection();
table.addRowSelectionInterval(1, 1);
table.addRowSelectionInterval(15, 15);
table.addRowSelectionInterval(28, 28);
...

setRowSelectionInterval, .

+3

It is not possible to set random selection with a single method call, you need more than one to perform this kind of selection

table.setRowSelectionInterval(1, 1);
table.addRowSelectionInterval(15, 15);
table.setRowSelectionInterval(28, 28);
table.addRowSelectionInterval(188 , 188 );

And so on....

+1
source

Here is a general way to do this:

public static void setSelectedRows(JTable table, int[] rows)
{
    ListSelectionModel model = table.getSelectionModel();
    model.clearSelection();

    for (int row : rows)
    {
        model.addSelectionInterval(row, row);
    }
}
+1
source

All Articles