How To Fill A JTable With Data From LinkedList Using Java NetBeans
In this Java Tutorial we will see How To Populate A JTable With A Linked List Of Object By Creating A User Class Using For Loop And DefaultTableModel In Java NetBeans .
Project Source Code:
// create a class to use with the linkedList
class User{
private String firstName;
private String lastName;
private int age;
public User(String fn, String ln, int ag){
this.firstName = fn;
this.lastName = ln;
this.age = ag;
}
}
public void populateTableWithLinkedList(){
// create a user linkedList
LinkedList<User> list = new LinkedList<>();
// create users
User u1 = new User("AA","BB",10);
User u2 = new User("BB","CC",20);
User u3 = new User("CC","DD",30);
User u4 = new User("DD","EE",40);
User u5 = new User("EE","FF",50);
User u6 = new User("LL","MM",80);
User u7 = new User("NN","TT",100);
// add the users to the list
list.add(u1);
list.add(u2);
list.add(u3);
list.add(u4);
list.add(u5);
list.add(u6);
list.add(u7);
// get jtable default model
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
// populate the jtable with the list
Object[] row;
for(int i = 0; i < list.size(); i++){
row = new Object[3];
row[0] = list.get(i).firstName;
row[1] = list.get(i).lastName;
row[2] = list.get(i).age;
model.addRow(row);
}
}
OutPut:
Download Projects Source Code