1

How do I pre-populate the first column of a JTable using AbstractTableModel?

I want to put in time-slots in the first column and then populate the other columns with something else.

Ok so the ChannelTableModel will be used by JTables in the GUI. Basically it sets time slots of 30mins from 6.30 - 24:00. The time slots have to be put in the first row of a JTable

In some way I need to set a variable 'row' to get the row values in the AbstractTableModel, which I'm finding difficult to do.

Below is the code so far.

Code:

import java.util.List;
import javax.swing.table.AbstractTableModel;


public class ChannelTableModel extends AbstractTableModel
{


    public ChannelTableModel(List<Program> schedule)
    {
        this.channel= schedule;
    }


    public int getColumnCount() 
    {
        return 3;
    }


    public int getRowCount() 
    {
        return 37;
    }


    public Object getValueAt(int rowIndex, int columnIndex) 
    {

        switch (columnIndex)
        {
        case 0: return 6+((row*30) / 60)+":"+(row % 2 == 0 ? "00" : "30") + " - " + (6 +(((row+1)*30) / 60)+":"+(row % 2 != 0 ? "00" : "30"));
        default: return "Not Available.";
        }

    }

}

How do I create the variable "row" to make the TableModel workable ?

Brian
  • 1,951
  • 16
  • 56
  • 101
  • AbstractTableModel is abstract and thus cannot be used without further implementation. Can you post some code to show what you are doing? – ControlAltDel Apr 12 '12 at 15:10
  • _How do I create the variable "row" to make the TableModel workable ?_ `rowIndex` which is passed as parameter to that method is the row ... why not use that one ? – Robin Apr 12 '12 at 15:43
  • See also [`EnvTableTest`](http://stackoverflow.com/a/9134371/230513). – trashgod Apr 12 '12 at 18:21

1 Answers1

0

Often you'll just special case the first column. e.g., if the "real data" is in a matrix. Schematically:

public class AddColumn0TableModel extends AbstractTableModel {

    final int columnCount, rowCount;
    final Object wrappedData[][];

    public AddColumn0TableModel(Object[][] wrappedData) {
       this.wrappedData = wrappedData;
       //  assume nice square data, YMMV
       columnCount= 1 + wrappedData.length;
       rowCount = wrappedData[0].length;
    }

    public int getRowCount() { return rowCount; }

    public int getColumnCount() { return columnCount; }

    public Object getValueAt(int row, int column) {
       if (column == 0)
         // implement this, in your case the time slot
         return theSpecialThingForColumn0(row);
       else
          return wrappedData[column-1][row];
    }

}

p.s. there is a 50/50 chance I have the ordering wrong on the matrix compared to your ordering. :-)

user949300
  • 15,364
  • 7
  • 35
  • 66