How can I check if a row is selected?

I have a button click event on which I get the column value if a row is selected Table. But if I do not select the line and press the button, I get the error: java.lang.ArrayIndexOutOfBoundsException:-1My question is: how can I check if the pseudo-code line was selected: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.

+4
source share
3 answers

Stop and think about your problem before you are tempted to post a message. Take a break in coding if you need to - as soon as you take a break, the solution to the problem often appears 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
}
+11

, getSelectedRow() -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);
   }
}
+1

Source: https://habr.com/ru/post/1546632/


All Articles