简体   繁体   English

如果选择了任何行,则为JTable

[英]JTable if any row is selected

I am trying to figure out how to add logic to a JTable via an "if" statement that checks to see if ANY row is selected. 我试图弄清楚如何通过“if”语句向JTable添加逻辑,该语句检查是否选择了任何行。 I know how to check if a specific row is selected but I can't seem to figure out how to check all rows. 我知道如何检查是否选择了特定行,但我似乎无法弄清楚如何检查所有行。

if(tbl.isRowSelected(0)){

Obviously that is checking for a specific row. 显然,这是检查特定行。

I've also tried something like 我也试过类似的东西

if(tbl.isRowSelected(0-2000)){

This did not work nor did I expect it to work. 这不起作用,我也不希望它起作用。

The reason for this is that I'm setting up the table so that when the user clicks a row and then hits an "edit" button a second table will appear with more data related to the row they selected. 这样做的原因是我正在设置表,以便当用户单击一行然后点击“编辑”按钮时,将出现第二个表,其中包含与所选行相关的更多数据。 (Gets complicated here with 2D arrays inside of a hash map but I first need to get by this simple problem). (这里使用哈希映射中的2D数组变得复杂,但我首先需要解决这个简单的问题)。

Thanks for the help in advance! 我在这里先向您的帮助表示感谢!

This should be possible with a ListSelectionModel , which can be retrieved using JTable::getSelectionModel() 这应该可以使用ListSelectionModel ,可以使用JTable::getSelectionModel()检索

So you can call table.getSelectionModel().isSelectionEmpty() to find out if any row is selected. 因此,您可以调用table.getSelectionModel().isSelectionEmpty()来查找是否选择了任何行。

Use : 采用 :

 table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
        public void valueChanged(ListSelectionEvent event) {
            // do some actions here, for example
            // print first column value from selected row
            System.out.println(table.getValueAt(table.getSelectedRow(), 0).toString());
        }
    });

use table.getSelectedRow() it returns the index of the selected row and getSelectedColumn() return the selected columns 使用table.getSelectedRow()它返回所选行的索引,getSelectedColumn()返回所选列

and there is getSelectedRows() it return index arrays of selected rows 并且有getSelectedRows()它返回所选行的索引数组

int[] indexs=table_name.getSelectedRows();
//all the selected row are here no need to go throw 
//all your rows to see if they are selected or not
for(int index_row:rows){
   //you code here
 }

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

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