Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data from a JTable?

OK, I want to get all the data from the first column of a JTable. I though the best way would be pulling it in to a ArrayList, so I made one. I also made an instance of a 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 (cue screams). What am i doing wrong?

like image 499
Primm Avatar asked Aug 04 '12 21:08

Primm


People also ask

How do I get the value of a JTable cell?

Obtaining Cell Values To get the value from a particular grid cell, you can use the wValue property of the JTable object. The property has the Row and Column parameters which specify the row and the column that contain the cell.

How do I search for a JTable?

We can implement the search functionality of a JTable by input a string in the JTextField, it can search for a string available in a JTable. If the string matches it can only display the corresponding value in a JTable. We can use the DocumentListener interface of a JTextField to implement it.

What is JTable used for?

The JTable is used to display and edit regular two-dimensional tables of cells. See How to Use Tables in The Java Tutorial for task-oriented documentation and examples of using JTable .


2 Answers

I don't know those classes well, but I would guess you'll have to count from zero:

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

In Java, it is usual to count from 0 (like in most C-like languages)...

like image 123
Cedric Reichenbach Avatar answered Oct 07 '22 18:10

Cedric Reichenbach


It is best if you could post SSCCE that shows model initialization and its population with data. Also include details of the exception as there could be multiple sources for the problem.

Here is a demo based on @CedricReichenbach correction:

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); 
    }
}

The result is:

[1, 2]
like image 43
tenorsax Avatar answered Oct 07 '22 18:10

tenorsax