Populating a JTable with a Collection (List)

Below is a method for populating a Jtable using a List(Collection)

Hope it will be helpful


private void DisplayData(List<productdetail>ProductsList) {
DefaultTableModel aModel = new DefaultTableModel() {
//setting the jtable read only

@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
//setting the column name
Object[] tableColumnNames = new Object[2];
tableColumnNames[0] = “Product Name”;
tableColumnNames[1] = “Description”;

aModel.setColumnIdentifiers(tableColumnNames);
if (ProductsList == null) {
this.tbProducts.setModel(aModel);
return;
}

Object[] objects = new Object[2];
ListIterator<productsdetail> lstrg = ProductsList.listIterator();
//populating the tablemodel
while (lstrg.hasNext()) {
productsdetail newcus = lstrg.next();
objects[0] = newcus.getProductName();
objects[1] = newcus.getDescription();

aModel.addRow(objects);
}

//binding the jtable to the model
this.tbProducts.setModel(aModel);
}

Advertisements

11 thoughts on “Populating a JTable with a Collection (List)

  1. Nice work man. Please do you use Netbeans IDE. How do I populate jTable in Netbean after retrieve data from mysql database? I don’t want to do binding. And is it possible to any other collection object apart from Vector.
    Highly appreciate if you can help me. Thanks.

    • yes i use netbeans

      check this code

      private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
      // TODO add your handling code here:
      //getting connection to the database
      connectionManager con = new connectionManager();
      String name;
      Statement stmt;

      ResultSet rs; // execute query

      //defining the table model and columns
      DefaultTableModel dt = new DefaultTableModel();
      String[] col = new String[1];
      col[0] = “Last Names”;
      dt.setColumnIdentifiers(col);

      String[] row = new String[1];
      try {
      stmt = con.getConnection2().createStatement();
      rs = stmt.executeQuery(“Select lastname from Students where yeargroup=1”);

      while (rs.next()) {
      // parse the results
      name = rs.getString(“lastname”);
      row[0] = name;
      dt.addRow(row);
      //JOptionPane.showMessageDialog(null, name + “”);
      }
      this.jTable1.setModel(dt);
      } catch (SQLException ex) {
      Logger.getLogger(connectionFace.class.getName()).log(Level.SEVERE, null, ex);
      }

      }

  2. Thanks Gilbert, sorry for bothering u. I have these two questions:
    1. Is is possible to read data from mysql database into a class, put the class in an arraylist and then populate JTable from the Arraylist.

    2. Is it possible to automatically bind JTextfields to a class in Netbean as is do in Visual studio

  3. Thanks so much for your time. I am really new to java programming. Please, may be you should check these codes below out. Don’t really know where I went wrong.

    public class DatabaseTable extends javax.swing.JFrame {

    public DatabaseTable() {
    DefaultTableModel dtModel = new DefaultTableModel();

    //create header for table
    Object[] tableColumnNames = new Object[1];
    tableColumnNames[0] = “NAME”;
    //tableColumnNames[1] = “ID”;
    //tableColumnNames[2] = “AGE”;
    dtModel.setColumnIdentifiers(tableColumnNames);

    DBEngine dbengine = new DBEngine();

    //get data from database
    Object[] data = new Object[1];
    List personList = dbengine.populateListOfPerson();
    ListIterator lstrg = personList.listIterator();

    try {
    //populating the tablemodel
    while (lstrg.hasNext()) {
    Person p = lstrg.next();
    data[0] = p.getName();
    //data[1] = p.getId();
    //data[2] = p.getAge();
    dtModel.addRow(data);
    }
    //binding the jtable to the model
    this.jTable1.setModel(dtModel);

    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }

    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {

    public void run() {
    new DatabaseTable().setVisible(true);
    }
    });
    }
    // Variables declaration – do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration
    }

    ————————————————————
    public class DBEngine {

    Connection conn = null;
    LinkedList personList = new LinkedList();

    public DBEngine() {
    connectToDatabase();
    }

    private Connection connectToDatabase() {
    try {
    Class.forName(“com.mysql.jdbc.Driver”);
    String url = “jdbc:mysql://localhost:3306/personDb”;
    conn = DriverManager.getConnection(url, “root”, “”);
    } catch (ClassNotFoundException e) {
    // e.printStackTrace();
    //System.exit(1);
    } catch (SQLException e) {
    //e.printStackTrace();
    //System.exit(2);
    }
    return conn;
    }

    public List populateListOfPerson() {
    try {
    Statement st = conn.createStatement();
    ResultSet rs = st.executeQuery(“Select name From tbl1”);
    while (rs.next()) {
    Person person = new Person();
    person.setName(rs.getString(“name”));
    //person.setId(rs.getInt(“id”));
    // person.setAge(rs.getInt(“age”));
    personList.add(person);
    }
    rs.close();
    st.close();
    } catch (SQLException e) {

    }

    return personList;
    }
    }

    ————————————————————
    public class Person {
    private int id;
    private String name;
    private int age;

    public int getAge() {
    return age;
    }

    public void setAge(int age) {
    this.age = age;
    }

    public int getId() {
    return id;
    }

    public void setId(int id) {
    this.id = id;
    }

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    }

  4. this is my code but not display the data

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    String id = txtID.getText().toString();
    ArrayList employeeInfo = (ArrayList) employee.displayEmployee(id);
    if (employeeInfo.size() > 0) {
    for (int i = 0; i < employeeInfo.size(); i++) {
    HashMap hashmap = employeeInfo.get(i);
    DefaultTableModel amod = new DefaultTableModel();
    //setting the column name
    Object[] tableColumnNames = new Object[5];
    tableColumnNames[0] = "employee ID";
    tableColumnNames[1] = "First Name";
    tableColumnNames[2] = "Last Name";
    tableColumnNames[3] = "Age";
    tableColumnNames[4] = "Sex";
    amod.setColumnIdentifiers(tableColumnNames);
    Object[] objects = new Object[5];
    objects[0]=hashmap.get("id").toString();
    objects[1]=hashmap.get("firstName").toString();
    objects[2]=hashmap.get("lastName").toString();
    objects[3]=hashmap.get("age").toString();
    objects[4]=hashmap.get("sex").toString();
    amod.addRow(objects);
    tblEmployeeInfo.setModel(amod);
    JOptionPane.showConfirmDialog(null, tblEmployeeInfo);
    }
    }
    }

    • think its the sequence of your code

      try this:

      private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {

      // TODO add your handling code here: String id = txtID.getText().toString(); ArrayList employeeInfo = (ArrayList) employee.displayEmployee(id);

      DefaultTableModel amod = new DefaultTableModel(); //setting the column name Object[] tableColumnNames = new Object[5]; tableColumnNames[0] = "employee ID"; tableColumnNames[1] = "First Name"; tableColumnNames[2] = "Last Name"; tableColumnNames[3] = "Age"; tableColumnNames[4] = "Sex"; amod.setColumnIdentifiers(tableColumnNames);

      Object[] objects = new Object[5];

      if (employeeInfo.size() > 0) { for (int i = 0; i < employeeInfo.size(); i++) { HashMap hashmap = employeeInfo.get(i); objects[0]=hashmap.get("id").toString(); objects[1]=hashmap.get("firstName").toString(); objects[2]=hashmap.get("lastName").toString(); objects[3]=hashmap.get("age").toString(); objects[4]=hashmap.get("sex").toString(); amod.addRow(objects); }

      tblEmployeeInfo.setModel(amod); JOptionPane.showConfirmDialog(null, tblEmployeeInfo); }

      }

      Regards

      Gilbert Adjin Frimpong

      West-Legon (Accra)Cell: +233246893378

      Website:https://gilbertadjin.wordpress.com Mail:gilbert.adjin@yahoo.com Embrace Life’s Storm, they are part of the journey

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s