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?
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.
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.
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 .
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)...
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With