5

I have a button click event on which i am getting a column value, if a Table row is selected. But if i don't select the row and click the button i get the error: java.lang.ArrayIndexOutOfBoundsException:-1 my question is how can i check to see if a row has been selected pseudocode: if(Row == selected) { execute }

java code i have:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try 
        {
            int row = Table.getSelectedRow();
            String Table_click = (Table.getModel().getValueAt(row, 0).toString());            

           //... implementation hire   

        } catch (Exception e) 
        {
            JOptionPane.showMessageDialog(null, e);
        }        
    }  

Thank you for your help.

3 Answers3

14

Stop and think logically about your problem before you're tempted to post. Take a break from coding if you need to -- once you take a break, the solution to the problem often presents itself in short order.

int row = Table.getSelectedRow();

if(row == -1)
{
    // No row selected
    // Show error message
}
else
{
    String Table_click = (Table.getModel().getValueAt(row, 0).toString());
    // do whatever you need to do with the data from the row
}
MarsAtomic
  • 10,436
  • 5
  • 35
  • 56
  • 1
    just to add information: getSelectedRow Returns the index of the first selected row, -1 if no row is selected. – Robdll Mar 08 '16 at 10:33
1

When no row is selected, getSelectedRow() returns -1.

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
   try {
      int row = Table.getSelectedRow();
      if (row > -1) {
         String Table_click = (Table.getModel().getValueAt(row, 0).toString());
         //... implementation here
      }
   }
   catch (Exception e) {
      JOptionPane.showMessageDialog(null, e);
   }
}
gilly3
  • 87,962
  • 25
  • 144
  • 176
0

if row > -1 then you know a row has been selected. see: http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html#getSelectedRow()

Davie Brown
  • 717
  • 4
  • 23