In order to select a row, I use this code:
table_2.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent event1) {
if (event1.getButton() == MouseEvent.BUTTON3) {
Point point = event1.getPoint();
int column = table_2.columnAtPoint(point);
int row = table_2.rowAtPoint(point);
table_2.setColumnSelectionInterval(column, column);
table_2.setRowSelectionInterval(row, row);
}
}
});
Then, to reset the highlighted line, I use this code:
table_2.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent arg0) {
table_2.clearSelection();
}
});
But I would like to know, is there any other way to reset the highlighted line?
So I got:
table_2.getSelectedRow()==-1
In order to select a row, I use this code:
Easier way is to use:
table.changeSelection(row, column, false, false);
Then, to reset the highlighted line, I use this code:
When you click on another cell in the table there is no focusLost(..) event generated because focus is still on the table. There is no need to clear the selection because the selection is automatically cleared when you click on another row, using the code I suggested.
if (event1.getButton() == MouseEvent.BUTTON3) {
Don't use "MouseEvent.BUTTON3", people don't know what that means. Instead use
//if (SwingUtilties.isRightMouseButton( event1 ))
if (SwingUtilities.isRightMouseButton( event1 ))
which is easier to read and understand.