tayyab developer
tayyab developer

Reputation: 83

How To Remove Empty Rows In JTable Java

I am selecting records from the database and its showing some empty records in the JTable Along with the records I am not been able to filter records with table .

Here are some empty records which is in the image Empty Records

public ArrayList<User> getUsers(){

    ArrayList<User> usersList=new ArrayList<User>();
   Connection connection=getConnection();
    String query="SELECT * FROM info";
    Statement myState;
    ResultSet rs;
    try{
    myState=connection.createStatement();
    rs=myState.executeQuery(query);

    User user;
    while(rs.next()){
            user=new User(rs.getInt("id"),rs.getString("fname"),rs.getString("lname"),rs.getInt("age"));
            usersList.add(user);
        }
    }
    catch(Exception ep){                        
        ep.printStackTrace();
    }
    return usersList;
}

I am populating these records in JTable with this function which is given below.

public void ShowUsersinJTable(){


    ArrayList<User> uList=getUsers();
    DefaultTableModel model=(DefaultTableModel)jTable1.getModel();
    Object[] row=new Object[4];
    for(int i=0;i<uList.size();i++){


        row[0]=uList.get(i).getId();
        row[1]=uList.get(i).getFname();
        row[2]=uList.get(i).getLname();
        row[3]=uList.get(i).Age();
          model.addRow(row);
   }
}

Upvotes: 3

Views: 3688

Answers (2)

Abdulwehab
Abdulwehab

Reputation: 1428

The default number of rows of the jTable in netbeans is four. So you can remove this by going to jTable properties -> model -> Rows.

enter image description here

enter image description here

Or, you can set rowCount to be zero before adding rows in the table like this:

DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);

Upvotes: 2

XtremeBaumer
XtremeBaumer

Reputation: 6435

as the code seems about right try changing your code to this:

ArrayList<User> uList=getUsers();
DefaultTableModel model=(DefaultTableModel)jTable1.getModel();
for(int i=0;i<uList.size();i++){
    Object[] row=new Object[4];

    row[0]=uList.get(i).getId();
    row[1]=uList.get(i).getFname();
    row[2]=uList.get(i).getLname();
    row[3]=uList.get(i).Age();
      model.addRow(row);
}

also you can delete all rows before filling the table (only needed if table was filled with data)

for (int i = table.getRowCount() - 1; i >= 0; i--) {
    model.removeRow(i);
}

please tell me if it has worked, so i can help you further if needed

Upvotes: 3

Related Questions