-2

I'm having trouble making a JTable that incorporates a hashmap instead of a multidimensional array. I'm using my own custom table class and get an error on the constructor. Here's the code for that class:

import javax.swing.table.DefaultTableModel;
import java.util.HashMap;

public class CustomTable extends DefaultTableModel {
    private String[] columnNames;
    private HashMap<Integer, Object[]> newData;

    public CustomTable(HashMap<Integer, Object[]> newData, String[] columnNames) {
        this.newData = newData;
        this.columnNames = columnNames;
    }

    public int getColumnCount() { return columnNames.length; }

    public int getRowCount() { return newData.size(); }

    public String getColumnName(int col) {
        return columnNames[col];
    }

    public Object getValueAt(int row, int col) {
        Object[] rowData = newData.get(row);
        return rowData[col];
    }

    public void setValueAt(Object value, int row, int col) {
        Object[] rowData = newData.get(row);
        rowData[col] = value;

        fireTableCellUpdated(row, col);
    }

    public void removeRow(int row) {
        newData.remove(row);
        fireTableRowsDeleted(row, row);
    }
}

Here's the error:

Exception in thread "main" java.lang.NullPointerException
    at CustomTable.getRowCount(CustomTable.java:21)
    at javax.swing.table.DefaultTableModel.setDataVector(DefaultTableModel.java:224)
    at javax.swing.table.DefaultTableModel.<init>(DefaultTableModel.java:124)
    at javax.swing.table.DefaultTableModel.<init>(DefaultTableModel.java:106)
    at javax.swing.table.DefaultTableModel.<init>(DefaultTableModel.java:86)
    at CustomTable.<init>(CustomTable.java:9)
    at ControlPanelUI.setupTable(ControlPanelUI.java:22)
    at ControlPanelUI.createRightCP(ControlPanelUI.java:106)
    at MovieStore.<init>(MovieStore.java:33)
    at MovieStore.main(MovieStore.java:16)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

1 Answers1

0

My first recommendation is don't use a HashMap. What is the point of the Integer as the key and then an Array as the data? The key will never be used in the model. Just Use an ArrayList.

Secondly, don't extend DefaultTableModel. That class already provides storage for the model and implementation of all the methods. There is no know to override all the methods again. Instead you should be extend AbstractTableModel.

Note your error message is referring to the setDataVector(...) method? You get this error because you are extending DefaultTableModel. If you instead extend AbstractTableModel the problem should go away.

camickr
  • 321,443
  • 19
  • 166
  • 288