在获取列和行选择时是否超出范围?

时间:2018-07-13 18:26:15

标签: java sql arrays jtable

我正在尝试使用单击的事件来获取JTable上选择的列和行,但这告诉我-“ java.lang.ArrayIndexOutOfBoundsException:-1”

这是我的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);

我尝试从JTable中获取来自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());
}

这是我的鼠标单击事件:

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

1 个答案:

答案 0 :(得分:4)

查看JTable的JavaDocs,如果未选择任何行,则JTable.getSelectedRow()方法将返回-1。

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

然后,您尝试将检索到的值与JTable一起使用,这可能导致ArrayOutOfBoundsException。

一个明显的解决方案是确保在调用该Event时选择了一行,因此不会返回-1。有关选择行的一些详细信息,请参见this