Suppose you have three arrays representing a set of points on the plane,
giving an index number and an x and y coordinate, and you would like
to manipulate them as a StarTable. One way is to use the
ColumnStarTable
class,
which gives you a table of a specified number of rows but initially
no columns, to which you can add data a column at a time.
Each added column is an instance of
ColumnData
;
the ArrayColumn
class
provides a convenient implementation which wraps an array of objects
or primitives (one element per row).
StarTable makeTable( int[] index, double[] x, double[] y ) { int nRow = index.length; ColumnStarTable table = ColumnStarTable.makeTableWithRows( nRow ); table.addColumn( ArrayColumn.makeColumn( "Index", index ) ); table.addColumn( ArrayColumn.makeColumn( "x", x ) ); table.addColumn( ArrayColumn.makeColumn( "y", y ) ); return table; }
A more general way to approach this is to write a new implementation of
StarTable
;
this is like what happens in Swing if you write your own
TableModel
to provide data for a
JTable
.
In order to do this you will usually want to subclass one of the existing
implementations, probably
AbstractStarTable
,
RandomStarTable
or
WrapperStarTable
.
Here is how it can be done:
class PointsStarTable extends RandomStarTable { // Define the metadata object for each of the columns. ColumnInfo[] colInfos_ = new ColumnInfo[] { new ColumnInfo( "Index", Integer.class, "point index" ), new ColumnInfo( "X", Double.class, "x co-ordinate" ), new ColumnInfo( "Y", Double.class, "y co-ordinate" ), }; // Member variables are arrays holding the actual data. int[] index_; double[] x_; double[] y_; long nRow_; public PointsStarTable( int[] index, double[] x, double[] y ) { index_ = index; x_ = x; y_ = y; nRow_ = (long) index_.length; } public int getColumnCount() { return 3; } public long getRowCount() { return nRow_; } public ColumnInfo getColumnInfo( int icol ) { return colInfos_[ icol ]; } public Object getCell( long lrow, int icol ) { int irow = checkedLongToInt( lrow ); switch ( icol ) { case 0: return new Integer( index_[ irow ] ); case 1: return new Double( x_[ irow ] ); case 2: return new Double( y_[ irow ] ); default: throw new IllegalArgumentException(); } } }In this case it is only necessary to implement the
getCell
method;
RandomStarTable
implements the other data access methods
(getRow
, getRowSequence
, getRowAccess
)
in terms of this.
Note that for more complicated behaviour, more methods may need
to be implemented.