Reputation: 718
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. 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).
Thanks for the help in advance!
Upvotes: 3
Views: 16007
Reputation: 14721
use table.getSelectedRow() it returns the index of the selected row and getSelectedColumn() return the selected columns
and there is getSelectedRows() it return index arrays of selected rows
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
}
Upvotes: 2
Reputation: 8200
This should be possible with a ListSelectionModel
, which can be retrieved using JTable::getSelectionModel()
So you can call table.getSelectionModel().isSelectionEmpty()
to find out if any row is selected.
Upvotes: 7
Reputation: 1332
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());
}
});
Upvotes: 3