Reputation: 249
My question is really simple, I just don't know how to query this on google.
What I want is just to print the selected row index when I click a row on a JTable
.
The problem is if I click a valid row index
(which is index >= 0 && index < rowCount
) and then I click outside of the valid rows on lower part of the table which has no rows (obviously it is now index < 0
) the row index that is printed is still the last valid row index that I clicked.
What I want for this is to print the "No row selected"
and clears the row selection when I clicked on the lower blank part of the table which has no rows.
(I am already clicking outside of the rows here on the lower blank part of the table)
Here is my codes:
JTable table = new JTable(new MyTableModel());
table.setFillsViewportHeight(true);
table.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int rowIndex = table.getSelectedRow();
if(rowIndex < 0) {
System.out.println("No row selected");
table.clearSelection();
} else {
System.out.println("Row " + rowIndex + " selected");
}
}
});
The only time that this simple program works the way I want it to do is when I set the setFillsViewportHeight
to false
or just omit it since it is false
by default.
So how can I do this while the table.setFillsViewportHeight
is set to true
?
Upvotes: 0
Views: 355
Reputation: 6307
You can use table.rowAtPoint(e.getPoint())
to get the clicked row. It will return -1
if the selection is not valid (When you click below the table):
public void mousePressed(MouseEvent e) {
//Updated to use rowAtPoint
int rowIndex = table.rowAtPoint(e.getPoint());
//Existing code
if(rowIndex < 0) {
System.out.println("No row selected");
table.clearSelection();
} else {
System.out.println("Row " + rowIndex + " selected");
}
}
Upvotes: 3