繁体   English   中英

Java Swing JTable以编程方式选择多行

[英]Java Swing JTable select programmatically multiple rows

我有一个多行的JTable,每一行都通过散点图上的Point显示。 我要做的是当在散点图上选择给定点时,我必须将此选择与JTable中相应行的选择相关联。

我有一个代表的Integer,我要强调哪一行。

我尝试的是:

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

所以这里的问题是这个方法选择给定范围内的所有行[index1,index2]。 我想选择例如行1,15,28,188等。

你是怎样做的?

要仅选择一行,请将其作为开始和结束索引传递:

table.setRowSelectionInterval(18, 18);

或者,如果要选择多个非连续索引:

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

或者,您可能会发现实现自己的ListSelectionModelListSelectionModel并使用它来跟踪表和散点图上的选择是一个更清晰的解决方案,而不是监听散点图并强制表匹配。

它也可以在不使用ListSelectionModel的情况下工作:

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

只是不要调用setRowSelectionInterval,因为它总是清除当前的选择。

无法通过一个方法调用设置随机选择,您需要多个才能执行此类选择

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

等等....

以下是实现此目的的通用方法:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM