import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.util.Vector;
import java.awt.Dimension;
public class TableJAVA extends JPanel
{
//Create Table Elements
/* There are a few important things when creating a JTable.
* 1) The Data Array. This is a 2D array that holds the row
* and column data.
* 2) The Column Names Array. This is a 1D array that holds
* the column names.
* 3) The JTable Object itself.
* 4) A Table Model, in this case a DefaultTableModel.
* 5) A JScrollPane to allow the table to be viewable
* completely.
*/
Object[][] data;
String[] columnNames;
JTable table;
DefaultTableModel model;
JScrollPane tableScroller;
/* To create a table of dynamic size, we need a dynamic data
* structure to hold a list of Object that will be represented
* in the table. For this example, it is Person Objects.
*/
Vector<Person> personList;
public TableJAVA()
{
super();
//Initialize Person List
personList = new Vector<Person>();
personList.add(new Person("First1", "Last1", 23, "Male"));
personList.add(new Person("First2", "Last2", 58, "Female"));
personList.add(new Person("First3", "Last3", 94, "Male"));
personList.add(new Person("First4", "Last4", 34, "Female"));
personList.add(new Person("First5", "Last5", 20, "Male"));
personList.add(new Person("First6", "Last6", 71, "Female"));
personList.add(new Person("First7", "Last7", 13, "Male"));
personList.add(new Person("First8", "Last8", 43, "Female"));
//Initialize Column Names Array
columnNames = new String[]{"First Name","Last Name","Age","Gender" };
//Initialize Data Array
data = new Object[personList.size()][columnNames.length];
//Fill Data Array
for(int i=0;i<personList.size();i++)
{
data[i][0] = personList.get(i).firstName;
data[i][1] = personList.get(i).lastName;
data[i][2] = personList.get(i).age;
data[i][3] = personList.get(i).gender;
}
//Initialize DefaultTableModel
model = new DefaultTableModel(data,columnNames);
//Initialize JTable
table = new JTable(model);
//Initialize Table Scroll Pane and set size
tableScroller = new JScrollPane(table);
tableScroller.setPreferredSize(new Dimension(450, 250));
//Remember to add the Table Scroller, not the JTable to the container
super.add(tableScroller);
// ----- Now let's add a new person -----
Person newPerson = new Person("First9", "Last9", 18, "Female");
//Remember to add to Person List for consistency
personList.add(newPerson);
//Now we add to the JTable
model.addRow(new Object[]{newPerson.firstName,newPerson.lastName,newPerson.age,newPerson.gender});
}
}