JAVA : Creating data table in java
Posted by Faheem Abbas on February 24, 2009
Since few week I am trying to work in java. It was always my dream to work in java when I
was university student and was doing my masters.
I was keen to complete my final year project in java but time didn’t allow us to get our
dreams true.
After working in php for more than year, I feel it would be worthy working in java, so
I m here to discuss one of its cool feature.
Creating data table in java is simple.
you will need to create an object of JTable, give it data and column names and that’s it.
let’s see how our code look like.
String[] columnNames = {“first name”,”last name”,”sports”};
Object[][] data = {{‘faheem’,”Abbas”,”Cricket”},{“shazil”,”Hassan”,”Soccer”}};
and now
JTable table = new JTable(data,columnNames);
getContentPane.add(JScrollPane(table));
it you want to have a table with some extra functionalities, you will need to create your our
own table model by extending it from AbstractTableModel and override some of the methods
provided by this abstract class.
I am giving its example as
class MyTableModel extends AbstractTableModel
{String[] columnNames = {“first name”,”last name”,”sports”};
Object[][] data = {{‘faheem’,”Abbas”,”Cricket”},{“shazil”,”Hassan”,”Soccer”}};
public int getColumnCount()
{return columnNames.length;
}
public int getRowCount()
{
return data.length;
}
public String getColumnName(int col)
{return columnNames[col];
}
public Object getValueAt(int row, int col)
{return data[row][col];
}
public boolean isCellEditable()
{
return true/false;
}
}
Now while creating object of JTable, write
JTable table = new JTable(new MyTableModel());
Asim Zeeshan said
I had no idea you were into Java too, nice article. thanks for sharing
Mihir said
Hello,
I want to bring data from MySQL database table into JTable.
Can you please tell me how?
Jonathan said
You might like GWT .
Franco said
with C# it’s easy to create a data table,
…
DataTable dt = new DataTable();
dt.TableName = “easy”;
DataRow row;
DataColumn cl = new DataColumn();
cl.DataType = System.Type.GetType(“System.String”);
dt.Columns.Add(cl);
row = dt.NewRow;
dt.Rows.Add(row);
dt.Rows[0][0] = “ciao”;