Archive | JAVA RSS feed for this section

JAVA : Creating data table in java

24 Feb

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());