1

I am trying to get what column and row are selected on a JTable using a clicked Event, but its telling me this - "java.lang.ArrayIndexOutOfBoundsException:-1"

Here is my JTable:

DefaultTableModel tabelaPrs = new DefaultTableModel (null, new String[] {"DATA","EXERCICIO","PESO","NÚMERO DE REPETIÇÕES"});
JTable jtPrs = new JTable(tabelaPrs);
jtPrs.setEnabled(false);
JScrollPane jspPrs= new JScrollPane(jtPrs);
jspPrs.setEnabled(false);
jspPrs.setBounds(55,88,639,567);
jspPrs.setPreferredSize(new Dimension(475,125));
contentPane.add(jspPrs);

My try catch to give the JTable the data from sql:

try
{
    java.sql.Statement stmt;
    ResultSet rs;
    String sql = "SELECT * FROM prs ORDER BY data";
    int i = 0;
    String [] campos = new String [] {null, null, null,null};

    LigacaoBD obterLigacao = new LigacaoBD();
    Connection con = (Connection) obterLigacao.OL();

    stmt = con.createStatement();
    rs = stmt.executeQuery(sql);

    while (rs.next())
    {
        tabelaPrs.addRow(campos);
        tabelaPrs.setValueAt(rs.getString("data"), i, 0);
        tabelaPrs.setValueAt(rs.getString("exercicio"), i, 1);
        tabelaPrs.setValueAt(rs.getString("peso"), i, 2);
        tabelaPrs.setValueAt(rs.getString("num_reps"), i,3);
        i++;
    }
    obterLigacao.FecharLigacao(con);
}
catch (SQLException sqle)
{
    JOptionPane.showMessageDialog(null, "Não foi possivel efetuar a operação na BD." + sqle.getMessage());
}

Here is my Mouse Clicked Event:

jtPrs.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {

            int r = jtPrs.getSelectedRow();

            getData = tabelaPrs.getValueAt(r, 1).toString();
            getExercicio = tabelaPrs.getValueAt(r, 2).toString();
            getPeso = tabelaPrs.getValueAt(r, 3).toString();
            getRepetições = tabelaPrs.getValueAt(r, 4).toString();
        }
    });
Nathalia Soragge
  • 1,415
  • 6
  • 21
In Yumen
  • 31
  • 7

1 Answers1

4

Looking at the JavaDocs for JTable, the method JTable.getSelectedRow() returns -1 if no row is selected.

int r = jtPrs.getSelectedRow(); getData = tabelaPrs.getValueAt(r, 1).toString();

You then attempt to use the retrieved value with the JTable, which probably caused the ArrayOutOfBoundsException.

The obvious solution is to make sure a row is selected when that Event is called, so that -1 won't be returned. See this for some details about selecting a row.

Alex Lin
  • 94
  • 2