Search code examples
javaswingjtablenullpointerexceptionabstracttablemodel

To Display data from text file to JTable


My Text file contain data as: sample.txt
MEMHEAD 1 1 NA SetString srcCode

MEMHEAD 1 2 NA SetString memIdnum

LGLNAME 1 5 NA SetString onmfirst

I have created MyClassModel class extending AbstractTableModel as:

    public class MyClassModel extends AbstractTableModel 
{

    Vector data;
    Vector columns;
    public MyTableModel() {
            String line;

            try {
                    FileInputStream fis = new FileInputStream("sample.txt");
                    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                    StringTokenizer st1 = new StringTokenizer(br.readLine(), ",");
                    while (st1.hasMoreTokens())
                           columns.addElement(st1.nextToken());
                    while ((line = br.readLine()) != null) {
                            StringTokenizer st2 = new StringTokenizer(line, ",");
                            while (st2.hasMoreTokens())
                                    data.addElement(st2.nextToken());
                    }
                    br.close();
            } catch (Exception e) {
                    e.printStackTrace();
            }
    }

    public int getRowCount() {
            return data.size() / getColumnCount();
    }

    public int getColumnCount() {
            return columns.size();
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
            return (String) data.elementAt((rowIndex * getColumnCount())
                            + columnIndex);
    }
}
}

In this way I retrieved data from a file. Now when I make a JTable and set model using table.setModel(MyTableModel). I am getting a NullPointerException.

CONTINUED:

The text file data is being displayed in the JTable but JTable also contains some extra rows with some junk data and when I press on those rows java.lang.ArrayIndexOutOfBoundsException: 180 >= 180 this exception is thrown. However, I Found out that there is some problem with the line

public Object getValueAt(int rowIndex, int columnIndex) {
        return (String) data.elementAt((rowIndex * getColumnCount()) + columnIndex);
}

But dont know what is the problem.Please help.


Solution

  • You are adding data to both Vectors with out initializing them.

    Vector data;
    Vector columns;
    

    Initialize them before you add elements.

    Vector data = new Vector();
    Vector columns = new Vector();
    

    Check after doing this whether you are getting NullPointerException or not.

    If still you are getting NPE then I doubt that you didn't initialize JTable. So post code to make us know where exactly exception is coming.