Douglas Grealis
Douglas Grealis

Reputation: 619

Creating a JTable in Java

The data I will be using for the JTable is an ArrayList of object data (e.g. Person) that will be returned using a method. Because the constructor of a JTable requires you to pass in an Object type multi-dimensional array, do I need to convert this ArrayList to a multi-dimensional array? Either case, how can I go about creating a JTable from an ArrayList of Object data?

Thanks much appreciated

Upvotes: 0

Views: 189

Answers (2)

eatSleepCode
eatSleepCode

Reputation: 4637

you can try this code. And set your JTables model from this method.


public TableModel toTableModel() {
    Object[] headerNames = new Object[] { "a", "b" };
    DefaultTableModel model = new DefaultTableModel(headerNames, 0);
    List<String> valueList = new ArrayList<String>();
    valueList.add("a");
    valueList.add("b");
    model.addRow(valueList.toArray());
    return model;
}

Upvotes: 2

sanbhat
sanbhat

Reputation: 17622

It can be done using DefaultTableModel (without requiring multi-dimensional array)

String columns = new String[] {"Name", "Age"};
ArrayList<Person> data = getYourData();

DefaultTableModel dm = new DefaultTableModel(data.size(), columns.length);
JTable table = new JTable(dm);

for(Person p : data) {
   table.addRow(new String[]{p.name, p.age});
}

see this question for additional info

Upvotes: 2

Related Questions