问题
I have used a tutorial to see how to implement JTable but I don't know how exactly access the data of each cell to extract the data that the user put in these.
The table has 2 column and N rows
In the first column there is a String in the second there is a int
The tutorial that I have used is this
回答1:
Every JTable
has a data-model connected with it. Users may add data to this data model (e.g. by calling to the javax.swing.table.TableModel.setValueAt(Object, int, int)
method) and JTable
then displays them. In order to process the data from the JTable
one can use the following approach:
JTable t = new JTable(/* set some table-model that will contain the data */);
...
/* get some table-model that will contain the data */
TableModel tm = t.getModel();
for (int i = 0; i < tm.getRowCount(); i++) {
for (int j = 0; j < tm.getColumnCount(); j++) {
Object o = tm.getValueAt(i, j);
if (o instanceof Integer) {
System.out.println((Integer)o);
} else if (o instanceof String) {
System.out.println((String)o);
}
}
}
回答2:
You have to see the paragraph "Listening for Data Changes"
In general, you have to get the model associated with the table and call it "getValueAt" method. It returns the Object associated with the cell, so you have to cast it to String or Integer. For example if you want to get the value of the second column and third row, the code is:
(Integer) model.getValueAt(2,1)
来源:https://stackoverflow.com/questions/10061964/how-to-access-the-data-of-each-cell-in-a-jtable