Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 反转JTable中的选择_Java_Swing_Jtable_Selection_Invert - Fatal编程技术网

Java 反转JTable中的选择

Java 反转JTable中的选择,java,swing,jtable,selection,invert,Java,Swing,Jtable,Selection,Invert,单击一个按钮,我希望所选行被反转(非所选行应被选中,所选行应被非选中) JTable中有内置方法吗?JTable没有该功能不,您必须实现cutsomJTable似乎没有内置的方法来实现这一点。所以我用下面的代码实现了它。(希望这对面临类似问题的人有所帮助。) int[]selectedindex=jtable.getSelectedRows(); jtable.selectAll(); 对于(int i=0;i

单击一个按钮,我希望所选行被反转(非所选行应被选中,所选行应被非选中)


JTable中有内置方法吗?

JTable没有该功能

不,您必须实现cutsom

JTable似乎没有内置的方法来实现这一点。所以我用下面的代码实现了它。(希望这对面临类似问题的人有所帮助。)

int[]selectedindex=jtable.getSelectedRows();
jtable.selectAll();
对于(int i=0;i
要简化Sudar的解决方案:

int[] selectedIndices = table.getSelectedRows();
table.selectAll();
for (int prevSel : selectedIndices) {
    table.removeRowSelectionInterval(prevSel, prevSel);
}

上面的改进是使用选择模型对象而不是表对象更新选择。当您通过表更新选择时,每次更新都会触发一个选择更改事件,并且只需几秒钟就可以更新一个只有几百行的表

对于超过几百行的表,最快的方法是

/**
 * Invert selection in a JTable.
 *
 * @param table
 */
public static void invertSelection(JTable table) {
    ListSelectionModel mdl = table.getSelectionModel();
    int[] selected = table.getSelectedRows();
    mdl.setValueIsAdjusting(true);
    mdl.setSelectionInterval(0, table.getRowCount() - 1);
    for (int i : selected) {
        mdl.removeSelectionInterval(i, i);
    }
    mdl.setValueIsAdjusting(false);
}

添加您的解决方案作为投票结果:请注意,对于较大的表,ListSelectionModel的valueIsAdjusting属性有助于提高性能。
/**
 * Invert selection in a JTable.
 *
 * @param table
 */
public static void invertSelection(JTable table) {
    ListSelectionModel mdl = table.getSelectionModel();
    int[] selected = table.getSelectedRows();
    mdl.setValueIsAdjusting(true);
    mdl.setSelectionInterval(0, table.getRowCount() - 1);
    for (int i : selected) {
        mdl.removeSelectionInterval(i, i);
    }
    mdl.setValueIsAdjusting(false);
}