How can i check to see if a row has been selected?

user3747557 picture user3747557 · Jul 1, 2014 · Viewed 11.6k times · Source

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.

Answer

MarsAtomic picture MarsAtomic · Jul 1, 2014

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
}