Selecting a row in jTable generates error

本小妞迷上赌 提交于 2020-03-16 07:29:31

问题


What i'm trying do here is that when i select a row in my table , after loading data , it should display the selected row's value in a text field (selectedRowTF). But as soon as i click on the jButton the following error generates -

java.lang.ArrayIndexOutOfBoundsException: -1

Since the error occurs even before the data is loaded , it leaves no chance for me to even select a row.

Also do you think I'm using the correct code to get the row's value?

Stack Trace

DefaultTableModel model;
model=(DefaultTableModel)tbl.getModel();
try {
    Class.forName("java.sql.Driver");
    Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/divign","root","password");
    Statement stmt=con.createStatement();

    int row=tbl.getSelectedRow();
    String rowSelected=(tbl.getModel().getValueAt(row, 0).toString());

    String query="SELECT * FROM CUSTOMER WHERE CUSTOMER_ID = '"+customerIdTF.getText()+"' ;";

    ResultSet rs=stmt.executeQuery(query);
    if(rs.next()) {
        model.addRow (new Object[ ] {
            rs.getInt(1),rs.getString(2),rs.getString(3)
            });
        selectedRowTF.setText(""+rowSelected);  
    }
    rs.close();
    stmt.close();
    con.close();
}
catch(Exception e){
    JOptionPane.showMessageDialog(null,e.toString());
}

回答1:


If you just load your data, the tbl.getSelectedRow() returns -1.

After that you try to get the string value of the first column of your invalid row.

String rowSelected=(tbl.getModel().getValueAt(row, 0).toString());

=> that getValueAt leads to your exception.

Try the following:

String rowSelected = "";
if(row != -1)
{
    rowSelected = tbl.getModel().getValueAt(row, 0).toString();
}

EDIT As you said you just want to get the selected value, the position of your code is wrong.

You are trying to get the value of the selected row at the time you are loading your data. But at that time you don't select a row. I think you need something like that (Value is printed out on a mouse click at the table):

tbl.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent evt) {
        int row = table.getSelectedRow();
        if (row > -1) {
            String value = (table.getModel().getValueAt(row, 0).toString());
            System.out.println("Value of row " + row + " col 0: '" + value + "'");
            selectedRowTF.setText(value);
        } else {
            System.out.println("Invalid selection");
        }
    }
});

Or you can react on the selection with a button click:

private void btClickActionPerformed(java.awt.event.ActionEvent evt) {                                        
    int row = table.getSelectedRow();
    if (row > -1) {
        String value = (table.getModel().getValueAt(row, 0).toString());
        System.out.println("Value of row " + row + " col 0: '" + value + "'");
        selectedRowTF.setText(value);
    } else {
        System.out.println("Invalid selection");
    }
}   



回答2:


Your situation is that when you called tbl.getSelectedRow(), it returned -1. That is a sentinel value to indicate that no row is selected. A row is selected when the mouse clicks on it, or when the keyboard moves the selection to it. You will need to handle the situation when no row is selected. I don't know your requirements and goals, so I can't advise on how to do that. You can register a selection listener with the JTable if you want to be notified when the selection changes and react to it. (See getSelectionModel, addListSelectionListener, and ListSelectionListener)

You may get away without handling it if you didn't enable sorting or filtering on your JTable, however it is worth knowing that the row indexes in the view (JTable) are not the same indexes in the model (DefaultTableModel). Use the convertRowIndexToModel method to convert from the view's index (as reported by getSelectedRow()) to the model's index (required by getValueAt()).

The code you posted also contains SQL Injection issues. I recommend researching that topic, and fix it using a PreparedStatement and setString().



来源:https://stackoverflow.com/questions/34201815/selecting-a-row-in-jtable-generates-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!