What i\'m trying do here is that when i select a row in my table , after loading data , it should display the selected row\'s value in a text field (selectedRowTF). But as soon
Your situation is that when you called tbl.getSelectedRow()
, it returned -1
. That is a sentinel value to indicate that no row is selected. A row is selected when the mouse clicks on it, or when the keyboard moves the selection to it. You will need to handle the situation when no row is selected. I don't know your requirements and goals, so I can't advise on how to do that. You can register a selection listener with the JTable if you want to be notified when the selection changes and react to it. (See getSelectionModel, addListSelectionListener, and ListSelectionListener)
You may get away without handling it if you didn't enable sorting or filtering on your JTable, however it is worth knowing that the row indexes in the view (JTable
) are not the same indexes in the model (DefaultTableModel
). Use the convertRowIndexToModel method to convert from the view's index (as reported by getSelectedRow()
) to the model's index (required by getValueAt()
).
The code you posted also contains SQL Injection issues. I recommend researching that topic, and fix it using a PreparedStatement and setString().