Addind content in JTable
by Arxleol on Tuesday 03.11.2009, under Java, tutorial
Java tutorial on this subject is complex and long opposite to other java tutorials. And as I have problem figuring this out, let me share with you probably the simplest way of inputting content into JTable.
First thing you need is DefaultTableModel. We will initialize one object named mod.
DefaultTableModel mod = new DefaultTableModel();
Next step is entering column names. As usual you want to represent some sort of data in table. Now let’s say we want to enter some student data in the table.
mod.addColumn("Name"); mod.addColumn("Surname"); mod.addColumn("Student ID"); mod.addColumn("Dorm"); mod.addColumn("Room number");
So we will have five columns named Name, Surname, Student ID, Dorm, Room number. Now we need to enter data in rows of table. We will do this by initializing Object array. I strongly suggest that the size of this array is as the number of columns therefore 5.
Object[] data = new Object[5];
Now we need to fill out this array with data.
data[0]="John"; data[1]="Doe"; data[2]="666"; data[3]="F"; data[4]="203";
Now as we this array filled out next step is to add it in the row of table.
mod.addRow(data);
If you want to add more rows then I suggest you wrap previous two code blocks into some loop. As shown below.
do{ data[0]="John"; data[1]="Doe"; data[2]="666"; data[3]="F"; data[4]="203"; mod.addRow(data); i++; }while(i<5);
Technically this code will add five same rows. But if you read data from somewhere else then you will be able to enter different data. Point here was to show how you may enter several rows one behind the other.
Final thing we need to do is to set our model (mod) as default model for table and data will appear in it.
jTable1.setModel(mod);
Now, sometimes you might not obtain desired result so you should just refresh table and your content will appear.