Search code examples
javaswingjtabledefaulttablemodel

accessing vector inside a vector in Java


I have populated a jTable from a database, now i want to add more functiaonality, I want to delete a row, i have my data structure like this:

public Vector getUser()throws Exception {

Vector<Vector<String>> userVector = new Vector<Vector<String>>();

Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
PreparedStatement pre = conn.prepareStatement("SELECT * FROM korisnici");
 rs = pre.executeQuery();


while (rs.next()) {
    Vector<String> user = new Vector<String>();
    user.add(rs.getString(1)); 
    user.add(rs.getString(2)); 
    user.add(rs.getString(3)); 
    user.add(rs.getString(4)); 
    userVector.add(user);
}

if (conn!=null)
    conn.close();

return userVector;
}

next I created a jTable with model like this

jTable1.setModel(new javax.swing.table.DefaultTableModel(
        data,header
    ));

so now i want to delete row using

jTable1.remove(int);

My db has 7 rows and when i put int=1 i get outOfBoundsException:1

I'm acesing it wrong, right? How do i remove a row, properly?


Solution

  • To remove a row from the table, you want

    ((DefaultTableModel)jTable.getModel()).removeRow(rowToRemove);
    

    The JTable itself is really just some display logic: it's the table model underneath that controls the data, and it's that that you need to interact with. The table itself will then render whatever's present in the table model.

    Since you're creating the DefaultTableModel yourself, the easier overall way of achieving this would be to set the model via

    DefaultTableModel model = new DefaultTableModel(data,header);
    jTable1.setModel(model);
    

    and then later on

    model.removeRow(rowToRemove);
    

    That saves you querying the table to find the table model every time.