SparseTableModel.java Source code

Java tutorial

Introduction

Here is the source code for SparseTableModel.java

Source

import java.awt.BorderLayout;
import java.awt.Point;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;

class SparseTableModel extends AbstractTableModel {

    private Map<Point, Object> lookup;

    private final int rows;

    private final int columns;

    private final String headers[];

    public SparseTableModel(int rows, String columnHeaders[]) {

        this.rows = rows;
        this.columns = columnHeaders.length;
        headers = columnHeaders;
        lookup = new HashMap<Point, Object>();
    }

    public int getColumnCount() {
        return columns;
    }

    public int getRowCount() {
        return rows;
    }

    public String getColumnName(int column) {
        return headers[column];
    }

    public Object getValueAt(int row, int column) {
        return lookup.get(new Point(row, column));
    }

    public void setValueAt(Object value, int row, int column) {
        if ((rows < 0) || (columns < 0)) {
            throw new IllegalArgumentException("Invalid row/column setting");
        }
        if ((row < rows) && (column < columns)) {
            lookup.put(new Point(row, column), value);
        }
    }
}

public class SparseTableModelDemo {
    public static void main(String[] a) {

        String headers[] = { "A", "B" };
        TableModel model = new SparseTableModel(10, headers);
        JTable table = new JTable(model);
        model.setValueAt("1", 0, 0);
        model.setValueAt("2", 9, 0);
        model.setValueAt("3", 5, 1);
        model.setValueAt("4", 8, 1);

        JFrame frame = new JFrame("Fixed Column Table");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(new JScrollPane(table), BorderLayout.CENTER);
        frame.setSize(300, 150);
        frame.setVisible(true);
    }
}