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");
}
}