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
If you just load your data, the tbl.getSelectedRow()
returns -1
.
After that you try to get the string value of the first column of your invalid row.
String rowSelected=(tbl.getModel().getValueAt(row, 0).toString());
=> that getValueAt
leads to your exception.
Try the following:
String rowSelected = "";
if(row != -1)
{
rowSelected = tbl.getModel().getValueAt(row, 0).toString();
}
EDIT As you said you just want to get the selected value, the position of your code is wrong.
You are trying to get the value of the selected row at the time you are loading your data. But at that time you don't select a row. I think you need something like that (Value is printed out on a mouse click at the table):
tbl.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
int row = table.getSelectedRow();
if (row > -1) {
String value = (table.getModel().getValueAt(row, 0).toString());
System.out.println("Value of row " + row + " col 0: '" + value + "'");
selectedRowTF.setText(value);
} else {
System.out.println("Invalid selection");
}
}
});
Or you can react on the selection with a button click:
private void btClickActionPerformed(java.awt.event.ActionEvent evt) {
int row = table.getSelectedRow();
if (row > -1) {
String value = (table.getModel().getValueAt(row, 0).toString());
System.out.println("Value of row " + row + " col 0: '" + value + "'");
selectedRowTF.setText(value);
} else {
System.out.println("Invalid selection");
}
}
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().