How to add a 1D array to a 2D array?
Solution 1
Your array :
int[][] array2d = {{1, 2, 3}, {6, 7, 8}};
is fixed in size, so you would have to create a copy with enough capacity to hold the new values:
int[][] newArray = Arrays.copyOf(array2d, 4);
newArray[2] = array1d;
newArray[3] = array1d2;
To add your data to the JTable
the arrays would have to be first converted to a non-primitive type such as an Integer
array. One option is to use the Apache Commons:
model.addRow(ArrayUtils.toObject(array));
for each row of the array.
Solution 2
arrays are fixed size so to append it you need to resize the array look at java.util.Arrays.
then set the arrays location
arra2d[index] = array1d;
is there are reason you are not using
TableModel.addRow(dataArray);
?
Related videos on Youtube
Giga Tocka
Updated on September 26, 2022Comments
-
Giga Tocka over 1 year
Sorry first time asking a question here.
If I have a 2D Array like this:
int[][] array2d = {{1, 2, 3}, {6, 7, 8}};
How do I add multiple 1D Arrays like this:
int[] array1d = {3, 2, 1}; int[] array1d2 = {8, 7, 6};
so that my original 2d array becomes this:
int[][] array2d = {{1, 2, 3}, {6, 7, 8}, {3, 2, 1}, {8, 7, 6}};
Note: this is for adding information from a JTextfield into a JTable whenever a button is pressed. So, the 2d array will be used as the data inside the table. If there is a better way to accomplish this I would appreciate it too. =)
-
reprogrammerYou should allocate enough rows in your 2D arrays. The way you initialize your 2D array, it cannot have more than 2 rows.
-
-
Giga Tocka over 11 yearsI'm just learning how to use JTables. From what I've learned I think I'm supposed to initialize JTables with a 1d array for columns and a 2d array for the data. I have no idea what TableModel.addRow(dataArray); does but I will look into it!
-
Giga Tocka over 11 yearsWell, what I'm trying to do is have a panel in which a user enters data. When a button is pressed, the data gets added to the table.
-
Reimeus over 11 yearsYou just need to split out your
Strings
into a format where you can build an object array so that you can use for youraddRow
call. Have a look at an example. This may require a new post. -
Giga Tocka over 11 yearsThanks a lot, this helped a lot.