CodeAngel
CodeAngel

Reputation: 579

swing jtable display a number of rows by default

I am developing a desktop application with java swing and NetBeans It uses a jtable with a custom table model to render data. I want to display a minimum number of rows with the table such that even when the actual number of rows to be displayed is less than the minimum value , the table should display additional dummy rows to make up the minimum number.

below are code nippets for the table model

public class MyTableModel extends AbstractTableModel {

    private List<List<Object>> dataList = new ArrayList<>();
     private String[] header = { "ID","SUBJECT","LETTTER FROM","LETTER DATE","DATE RECEIED",
                                  "REMARKS","DATE DISPATCHED","DESTINATION OFFICE"};


    public List<List<Object>> getDataList() {
        return dataList;
    }

    public void setDataList(List<List<Object>> dataList) {       
        this.dataList = dataList;
        fireTableDataChanged();       
        fireTableStructureChanged();        
    }

    public void setHeader(String[] header) {
        this.header = header;
    }

    public String[] getHeader() {
        return header;
    }

    @Override
    public int getRowCount() {
        return dataList.size();
    }

    @Override
    public int getColumnCount() {
        return header.length;
    }

    @Override
   public String getColumnName(int col) {
    return header[col];
   }

    @Override
    public Object getValueAt(int row, int col) { 
    return dataList.get(row).get(col);
    }

    @Override
     public Class<?> getColumnClass(int column)
        {
            for (int row = 0; row < getRowCount(); row++)
            {   
                Object o = getValueAt(row, column);

                if (o != null)
                {
                    return o.getClass();
                }              
            }
            return Object.class;
        }
    }

any suggestions available.

Upvotes: 0

Views: 2698

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

First, you need to return either the minRowCount or the number of rows, which ever is larger...

@Override
public int getRowCount() {
    return Math.max(dataList.size(), minRowCount);
}

Then you need to check if the request for a value is within the range of the data list

@Override
public Object getValueAt(int row, int col) { 
    Object value = null;
    if (row < dataList.size()) {
        value = dataList.get(row).get(col);
    }
    return value;
}

If you intend for the table to be editable, you will also need to adjust the isCellEditable and setValueAt methods

Upvotes: 5

Related Questions