tags:

views:

279

answers:

3

I would like to have a JFrame window with an initial empty table of say, 10 columns. An action event generated by a mouse click should then populate the table with a list of 10 or less items, the leaving the used rows of the table empty. How should this be done?

+4  A: 

I'd recommend defining your own TableModel implementation by subclassing AbstractTableModel. That way you can "back" your model with any suitable collection (e.g. java.util.List). When an ActionEvent is fired you would typically amend your underlying collection and then fire a TableModelEvent to cause the JTable to be repainted.

Adamski
Can you please give me a brief example?
Tony
@Vijay: http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#data
trashgod
A: 

Besides creating your own TableModel as explained by Adamski, you can use the javax.swing.table.DefaultTableModel directly.
It has a constructor which takes the number of columns and rows as argument and methods to manage the data (addRow, insertRow, setDataAt, ...).

I would prefer creating an own TableModel, unless it's for a very simple program/functionality.

Carlos Heuberger
+1  A: 

For this, you should create a DefaultTableModel with the data you want, and for the blank lines, you fill the object table with null values.

It´s simpler with some code:

As I don't know where you data come from, I'll presume it come from a matrix with less than 10 rows:

String data[][] = {{"a","b"}, {"c","d"}};

you have to create a new matrix with your previous data and the null cells for completion of the table. In the end You'll have something like this.

Object data2[][] = {{"a","b"}, 
{"c","d"}, 
{null,null}, 
{null,null}, 
{null,null}, 
{null,null}, 
{null,null}, 
{null,null}, 
{null,null}, 
{null,null}};

This way you'll have a 10x2 matrix that will fill your table. Now you can update your DefaultTableModel

yourTable.setModel(
        new DefaultTableModel(data2, new String [] {"Column1Title", "Cloumn2Title"}) {
        Class[] types = new Class[] {String.class,String.class}; 
        boolean[] canEdit = new boolean[] {true, true};
        @Override
        public Class getColumnClass(int columnIndex){ return types [columnIndex];}
        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex){ return canEdit [columnIndex];}
});

And that's it. I presume you don't have problems to create your Object matrix.

marionmaiden