javaswingarraylistjtabledefaulttablemodel

JTable populated from an ArrayList


What I am trying to do is to populate a JTable from an ArrayList.

The array list is a type Record which I have defined below:

public class Record {

    int Parameter_ID;
    int NDC_Claims;
    int NDC_SUM_Claims;

    public Record(int parameter, int claims, int ndc_sum_claims){
        Parameter_ID = parameter;
        NDC_Claims = claims;
        NDC_SUM_Claims = ndc_sum_claims;

    }

    public Record() {
        // TODO Auto-generated constructor stub
    }

I don't know how to populate the table with the column headers as well. This is what I have so far:

DefaultListModel listmodel = new DefaultListModel();
ArrayList<Record> test = new ArrayList<Record>();
DefaultTableModel modelT = new DefaultTableModel();
    Object data1[] = new Object[3];

    for(int i=0;  i<test.size();i++){
        data1[0] = test.get(i).Parameter_ID;
        data1[1] = test.get(i).NDC_SUM_Claims;
        data1[2] = test.get(i).NDC_Claims;
        modelT.addRow(data1);
    }

table_1 = new JTable(modelT, columnNames);
contentPane.add(table_1, BorderLayout.CENTER);
contentPane.add(table_1.getTableHeader(), BorderLayout.NORTH);

Nothing is outputted. Any help would be great!


Solution

  • Well you need to start by reading the API. You can't program if you don't read the API first.

    DefaultTableModel modelT = new DefaultTableModel();
    

    When you read the API what does that constructor do? It creates a model with 0 rows and 0 columns. You will want to create a model with 3 columns and 0 rows so that you can add rows of data to the model. Read the DefaultTableModel API

    table_1 = new JTable(modelT, columnNames);
    

    What does that statment do? I don't see a constructor that allows you to specify a model and column names so how does your code compile. You just want to create the table using the model.

    contentPane.add(table_1, BorderLayout.CENTER);
    contentPane.add(table_1.getTableHeader(), BorderLayout.NORTH);
    

    The table should be added to the viewport of a JScrollPane. The header will then be displayed as the column header of the scroll pane.

    Read the JTable API. The API also has a link to the Swing tutorial on How to Use Tables you need to read for the basics.

    ArrayList<Record> test = new ArrayList<Record>();
    

    You create an empty ArrayList. So what do you expect to happen when you iterate through the loop? How can you add data to the model if there is no data in the ArrayList?

    Also, did you search the forum/web for examples that use the DefaultTableModel or JTable classes. Those examples will help you write your code.