How to get data from JTable?

OK, I want to get all the data from the first JTable column. I, although the best way could have pulled him in ArrayList, so I made one. I also made an instance TableModel:

static DefaultTableModel model = new javax.swing.table.DefaultTableModel(); 
f.data.setModel(model); //f.data is the JTable

public static final void CalculateTotal(){
    ArrayList<String> numdata = new ArrayList<String>();

  for(int count = 1; count <= model.getRowCount(); count++){
      numdata.add(model.getValueAt(count, 1).toString());

  }
  System.out.println(numdata); 
}

This gives me a NullPointerException (scream scream) exception. What am I doing wrong?

+5
source share
3 answers

I do not know these classes very well, but I think you will have to count from scratch:

for (int count = 0; count < model.getRowCount(); count++){
  numdata.add(model.getValueAt(count, 0).toString());
}

In Java, it usually counts from 0 (as in most C-like languages) ...

+7
source

, SSCCE, . , .

@CedricReichenbach:

import java.util.ArrayList;
import java.util.List;

import javax.swing.table.DefaultTableModel;

public class TestModel {
    public static void main(String s[]) {
        DefaultTableModel model = new javax.swing.table.DefaultTableModel();    

        model.addColumn("Col1");
        model.addColumn("Col2");

        model.addRow(new Object[]{"1", "v2"});
        model.addRow(new Object[]{"2", "v2"});

        List<String> numdata = new ArrayList<String>();
        for (int count = 0; count < model.getRowCount(); count++){
              numdata.add(model.getValueAt(count, 0).toString());
        }

        System.out.println(numdata); 
    }
}

:

[1, 2]
+2

I know this answer was a bit late, but this is actually a very simple problem. Your code gives an error while reading the record, because there is no record in the table itself for the read code. Fill in the table and run your code again. The problem could be solved earlier, but from the code you posted it was not obvious what was inside your table.

+1
source

All Articles