Java Swing JTable select programmatically multiple rows

你说的曾经没有我的故事 提交于 2019-12-21 17:26:44

问题


I have a JTable with multiple rows and every row is presented via Point on a scatter plot. What I have to do is when a given point is selected on the scatter plot I have to associate this selection with selecting of the corresponding row in the JTable.

I have an Integer that represents, which row I have to highlight.

What I tried is:

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

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

How do you do that?


回答1:


To select just one row, pass it as both the start and end index:

table.setRowSelectionInterval(18, 18);

Or, if you want to select multiple, non-contiguous indices:

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

Alternately, you may find that implementing your own subclass of ListSelectionModel and using it to track selection on both the table and the scatterplot is a cleaner solution, rather than listening on the scatterplot and forcing the table to match.




回答2:


It also works without using the ListSelectionModel:

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

Just don't call the setRowSelectionInterval, as it always clears the current selection before.




回答3:


There is no way to set a random selection with a one 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....




回答4:


Here is a generic method to accomplish this:

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

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


来源:https://stackoverflow.com/questions/15556341/java-swing-jtable-select-programmatically-multiple-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!