I have been reading tutorials and I am still not sure so I will ask here. Is it possible to have a JTable with 2 columns where column 1 displays contents of an arraylist and column 2 displays numbers up to the size of the arraylist?. I have looked at tutorials but they dont really mention arraylists, so any sample codes or direction would be helpful. Thanks
Asked
Active
Viewed 5,747 times
2
-
1Consider starting with a JTable that only shows numbers in one column. That should be a simple incremental task, yes? Once you figure that out, take it from there. Regarding your specific question, if you want each row in the 2nd column to display the size of the arraylist, what goes in the 1st column? Is each row in the 1st column an entire arraylist? How do you want that content to be displayed in a single table cell? Start by posting a clearer description of EXACTLY what you are looking to do. – eternaln00b Feb 03 '12 at 18:31
-
it is clear - Column 1 displays each element of arraylist Column 2 displays numbers from 1 up until the size of the array list – M9A Feb 03 '12 at 18:36
-
1"It is clear" is not adequate. It may be clear to you, in your mind, but it sure isn't clear to me, or anyone else looking at this question which is probably why you've had plenty of views and not a single concrete response. You do realize that an "ArrayList" can have multiple elements, whereas the size of that ArrayList is just ONE integer? – eternaln00b Feb 03 '12 at 18:54
-
1 up to the size of the arraylist means 1, 2, 3, 4....arraylist.size. The answer below is enough hence no one has answered and it has votes. Speak for yourself, not others – M9A Feb 03 '12 at 19:49
1 Answers
4
Yes, of course it's possible. Implement a table model by extending AsbtractTableModel
, and use the list to implement its methods.
Read the JTable tutorial.
The main methods of the table model would look like this:
public Object getValueAt(int row, int column) {
if (column == 0) {
return this.list.get(row);
}
else {
return row;
}
}
public int getRowCount() {
return this.list.size();
}
public int getColumnCount() {
return 2;
}

JB Nizet
- 678,734
- 91
- 1,224
- 1,255
-
+1 This related [example](http://stackoverflow.com/a/9134371/230513) contans a `Map`. – trashgod Feb 03 '12 at 20:02
-
Im still having a hard time. Everytime I try to add my array of integers, it says an error as its not object[][] – M9A Feb 03 '12 at 21:58
-
@Matt9Atkins: I've added some code to the answer to get you started. You create a class extending AbstractTableModel, instantiate this class, and pass this instance to the constructor of JTable taking a TableModel as argument: http://docs.oracle.com/javase/6/docs/api/javax/swing/JTable.html#JTable%28javax.swing.table.TableModel%29 – JB Nizet Feb 03 '12 at 22:26