I have an array of buttons declared as a class variable that is added to a gridPane. When I try to remove the buttons of the array from the gridPane the event handler is being recognized but the node is not being removed.
Any ideas of how to accomplish this?
for(int i = 0; i < Rows; i++) {
for(int j = 0; j < Cols; j++) {
bArray = new Button[Rows][Cols];
bArray[i][j] = new Button();
bArray[i][j].setMinSize(20,20);
bArray[i][j].setMaxSize(25,25);
gridBoard.setVgap(1); //vertical gap in pixels
gridBoard.add(bArray[i][j], j, i);
bArray[i][j].setOnMouseClicked(e->checkNeighbors());
}
}
// Local Method
public static void checkNeighbors() {
// This print out statement is met, but the removal does not occur
System.out.println("Action is called");
gridBoard.getChildren().remove(bArray[0][1]);
gridBoard.getChildren().remove(bArray[0][2]);
gridBoard.getChildren().remove(bArray[0][3]);
}
You are overriding bArray in each iteration and the only valid references that are left at the end of the for loops are from [Rows][0] to [Rows][Cols].
As an example if Rows = 4 and Cols = 4, that would be that at the end the only valid references are [3][0], [3][1], [3][2] and [3][3], and you are trying to remove [0][1], [0][2], [0][3].
You should move the initialization of bArray before the loops start.
bArray = new Button[rows][cols];
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
bArray[i][j] = new Button();
// ......
}
Related
My goal is to implement the following method in parallel:
public static double[][] parallelAddMatrix(double[][] a, double[][] b), then test my program on randomly generated two lists of size 2000 x 2000. Finally I have to output the first 5 elements of matrix a and matrix b, and also the first five elements of the result matrix, which is what I'm having trouble with.
This is the part of my code where I create the first and second matrix.
public static void main(String[] args) {
int var1, var2;
final int matrices = 2000;
// creates first matrix
double[][] matrixA = new double[matrices][matrices];
for(var1 = 0; var1 < matrixA.length; var1++)
for (var2 = 0; var2 < matrixA[var1].length; var2++)
matrixA[var1][var2] = 1;
// creates second matrix
double[][] matrixB = new double[matrices][matrices];
for (var1 = 0; var1 < matrixB.length; var1++)
for (var2 = 0; var2 < matrixB[var1].length; var2++)
matrixB[var1][var2] = 1;
And then later created a function to create the result matrix...
public static double[][] parallelAddMatrix( double [][] a, double[][] b) {
//creates output matrix
double[][] resultMatrix = new double[a.length][a[0].length];
RecursiveAction task = new multiProcess(a, b, resultMatrix);
ForkJoinPool joinPool = new ForkJoinPool();
joinPool.invoke(task);
return resultMatrix;
}
How can I print out the first five elements for each of the three matrices?
I've tried stuff for the first and second matrix such as initializing var3, then under the "matrixA(orB)[var1][var2] = 1;", I put
for (var3 = 0; var3 < 5; var3++) {
System.out.println(var3);
}
and also tried
for (var3 = 0; var3 < 5; var3++) {
System.out.print(matrixA[var1][var2] + "");
}
System.out.println();
Please help on this, and please tell where it would be placed for each one (I might have trouble with brackets).
You'll need a nested for loop to iterate through the matrix, and a counter to see how many entries you've printed. Let's start with the easiest part: iterating over the matrix. I'll assume that the matrix is simply called matrix.
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]);
}
}
You probably already figured that out. Now we need a counter to count how many times we've printed out an entry from the matrix.
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]);
num_printed ++;
}
}
Ok. So now we need to stop once we've reached the end. We can't just use one break statement, because, we have two for loops.
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) { // iterate over the rows
for (int j = 0; j < matrix[i].length; j++) { // iterate over the columns
if (num_printed == 5) { // if we've already printed five items, stop
break;
} else { // otherwise, print the next item
System.out.println(matrix[i][j]);
num_printed ++; // increment the counter
}
}
if (num_printed == 5) { // so that we don't go to the next row
break;
}
}
It's worth noting that you could create your own separate method, and only use a return statement:
public void print_five_elements() {
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) { // iterate over the rows
for (int j = 0; j < matrix[i].length; j++) { // iterate over the columns
if (num_printed == 5) { // if we've already printed five items, stop
return;
} else { // otherwise, print the next item
System.out.println(matrix[i][j]);
num_printed ++; // increment the counter
}
}
}
}
More Specialized Approach
This approach allows you to use matrices that have less than five columns. However, since your matrix is 2000x2000, you could go for a much simpler approach. Use zero as the first index, and then just iterate up to five. Just keep in mind that this won't work if you have less than five columns:
public void print_five_elements_for_wide_matrix() {
for (int i = 0; i < 5; i++) {
System.out.println(matrix[0][i]);
}
}
Since the matrices are of size 2000 x 2000, you do not need nested loops to display first 5 elements from each of them.
int i;
//Display first 5 elements of matrixA
for(i=0; i<5; i++) {
System.out.print(matrixA[0][i] + " ");
}
System.out.println();
//Display first 5 elements of matrixB
for(i=0; i<5; i++) {
System.out.print(matrixB[0][i] + " ");
}
System.out.println();
double[][] result = parallelAddMatrix(matrixA, matrixB);
//Display first 5 elements of result
for(i=0; i<5; i++) {
System.out.print(result[0][i] + " ");
}
System.out.println();
Note that the above loops print the first 5 elements of the first row (i.e. row at index, 0) of each matrix. However, if you want to print the first element of the first 5 rows, just swap the indices e.g.
System.out.println(matrixA[i][0] + " ");
Try this:
Think of the first set of brackets as the row and the second set as the column.
for (int row = 0; row < 5; row++) {
for (int col = 0; col < 5; col++) {
System.out.print(matrixA[row][col] + " ");
}
System.out.println();
}
Since "multi-dimensional" arrays are really arrays of arrays you can do it like this if you wanted to print out the whole matrix
for (double[] row : matrixA) {
System.out.println(Arrays.toString(row));
}
Because of this, each row can be a different length. So you may have to get the length to print them out like you first wanted to.
for (int row = 0; row < matrixA.length; row++) {
for (int col = 0; col < matrixA[row].length; col++) {
System.out.print(matrixA[row][col] + " " );
}
}
Rows of different length of a "2D" array are known as ragged-arrays.
I want to Fill a 2D-Array with Javafx Labels in Which I can change the Text when I click it.
This is my actual Code but it's returning a NullPointer Exception.
Blockquote
`public static Label[][] initWelt() {
Label[][] welt = new Label[DIM1][DIM2];
for (int x = 1; x < welt.length - 1; x++) {
for (int y = 1; y < welt.length - 1; y++) {
if (Math.random() > 0.4) {
welt[x][y].setText("X");
}
else{
welt[x][y].setText(" ");
}
}
}
return welt;
}`
it's returning a NullPointer Exception.
The only thing the below code does is initialise a two-dimensional array, it doesn't populate the two-dimensional array, hence the NullPointerException occurs.
Label[][] welt = new Label[DIM1][DIM2];
Basically you can't call this:
welt[x][y].setText("X");
without populating the two-dimensional array with object references.
to overcome the problem first populate the two dimensional array, something like below:
Label[][] welt = new Label[DIM1][DIM2];
for(int i = 0; i < DIM1; i++){
for(int j = 0; j < DIM2; j++){
welt[i][j] = new Label();
}
}
then you can proceed with your current task at hand.
so now your code becomes like this:
public static Label[][] initWelt() {
Label[][] welt = new Label[DIM1][DIM2];
for(int i = 0; i < DIM1; i++){ //populate the array
for(int j = 0; j < DIM2; j++){
welt[i][j] = new Label();
}
}
for (int x = 0; x < DIM1; x++) {
for (int y = 0; y < DIM2; y++) {
if (Math.random() > 0.4) {
welt[x][y].setText("X");
}
else{
welt[x][y].setText(" ");
}
}
}
return welt;
}
Note - personally I think it would be better to refactor the current method and insert the code that populates the two-dimensional array in a different method.
I need a method that given input 2D array {{1,2},{3,4}} and (int)row=2; (int)column = 3, will produce a concatenated 2D array {{1,2,1,2,1,2}{3,4,3,4,3,4}}.
My attempt was to use a nested for loop to expand them both horizontally and and vertically, but was unsuccessful. This is what I have so far:
int row = 2;
int column = 5;
int count = 0;
int[][] list = {{12,3},{3,4}};
int [][] renewed = new int[row*list.length][column*list[0].length];
for (int l = 0; l<list.length; l++) {
for (int k = 0; k<renewed.length; k+= list.length) {
renewed[l+k] = list[l];
}
}
System.out.println(Arrays.deepToString(renewed));
}
}
^This produces list[][] expanded vertically, for the first column
int row = 2;
int column = 4;
int[][] list = {{12,3},{3,4}};
int [][] renewed = new int[row*list.length][column*list[0].length];
for (int i = 0; i<list[0].length; i++) {
for (int j = 0; j<renewed[0].length; j+=list[0].length) {
renewed[0][j+i] = list[0][i];
}
}
System.out.println(Arrays.toString(renewed[0]));
}
^This produces list[][] expanded horizontally, for the first row;
So how can I concatenate these two methods in order to produce a method that expands BOTH horizontally and vertically?
I think the easiest way is to iterate over every position in the new array and use the remainder operator % to get the right entry of the original.
int[][] list = {{1,2},{3,4}};
int row = 2;
int column = 5;
int [][] renewed = new int[row*list.length][column*list[0].length];
for (int i = 0; i < renewed.length; i++) {
for (int j = 0; j < renewed[0].length; j++) {
renewed[i][j] = list[i % list.length][j % list[0].length];
}
}
System.out.println(Arrays.deepToString(renewed));
So. I have a problem I simply cant get my head around.
I'm currently making a cellular automaton. (Java)
For this, I have 2 Arrays, one called cells[][] for current states,
and one called cellsX[][] for the temporary state inbetween steps.
at each update i do this:
public void updateCells() {
cellsX = cells;
for(int i = 0; i< Xsize; i++) {
for(int j = 0; j < Ysize; j++) {
cellsX[i][j].Update();
}
}
}
And later I render:
for(int i = 0; i< Xsize; i++) {
for(int j = 0; j < Ysize; j++) {
if(cells[i][j].isAlive()) {
int Colori[] = cells[i][j].GetColor();
g2d.setTransform(identity);
g2d.translate(0, 0);
g2d.setColor(new Color(Colori[0],Colori[1],Colori[2]));
g2d.drawRect((i*5)+20, (j*5)+20, 5, 5);
}
}
}
Right now, I would say nothing should happen, as I newer update cells[][]
but for some reason it do?
How can the cells[i][j] update, when the only cell I've given a command is cellsX[i][j]?
to show you the Update function in the Cell
public void Update() {
if(Info[0][0] > 0) {
Info[0][0] += 1;
Info[0][2] += rand.nextInt(2);
}
Info[1][0] ++;
if(Info[1][0] >255) Info[1][0] =0;
if(Info[0][0] > Info[0][1]) Info[0][0] = 0;
if(Info[0][2] <= 0) Info[0][0] = 0;
}
Its a void an no nothing to affect the outside world (Info[][] is an int array used to store data such as life and color (Info[1][0] is the red color)
I have no idea how the H. i can mess up. the creation of the cells and cellsX is
int Xsize = 100;
int Ysize = 100;
Cell[][] cells = new Cell[Xsize][Ysize];
Cell[][] cellsX = new Cell[Xsize][Ysize];
and initialized:
for(int i = 0; i< Xsize; i++) {
for(int j = 0; j < Ysize; j++) {
cellsX[i][j] = new Cell();
}
}
for(int i = 0; i< Xsize; i++) {
for(int j = 0; j < Ysize; j++) {
cells[i][j] = new Cell();
}
}
Sorry for the wall of text...
I just can't figure out how cells get's updated :S
From your comment -
"How should this not give me 2 2d arrays, one called cells and another
called cells X"
You do it's just that they equal each other here - cellsX = cells; Consider, and run/watch, this simple example...
public static void main(String[] args){
int size = 5;
int foo[][] = new int[size][size];
int bar[][] = new int[size][size];
for(int i = 0; i < size; ++i) {
for(int j =0; j < size; ++j) {
System.out.print(foo[i][j] + " ");
}
}
System.out.println();
foo = bar;
for(int i = 0; i < size; ++i) {
for(int j = 0; j < size; ++j) {
bar[i][j] = j;
}
}
for(int i = 0; i < size; ++i) {
for(int j =0; j < size; ++j) {
System.out.print(foo[i][j] + " ");
}
}
}//SSCCE1
Output:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 0 1 2 3 4
0 1 2 3 4 0 1 2 3 4 0 1 2 3 4
This shows that while I do have two 2D arrays they equal each other, they are not unique copies of each other. foo was a 2D array that was initialized by default to 0, but then we have foo reference bar. So the changes made to bar are reflected by foo. You want, I'm supposing, an independent copy initialized with the values of the other.
See that Arrays are Objects.
What you don't seem to understand is what the following line in your code does:
cellsX = cells;
Arrays in Java are objects. Variables hold references to objects. You just assigned the reference held in cells to cellsX. You now have two variables pointing to one array object. The array (and the arrays it contained) you originally instantiated and assigned to cellsX is gone; nothing references it and it will be garbage collected.
Consider the following:
public class Demo {
public static class MyPojo {
public int value;
public MyPojo(int value) {
this.value = value;
}
}
public static void main(String[] args) {
MyPojo pojoOne = new MyPojo(1);
MyPojo pojoTwo = new MyPojo(2);
System.out.println(pojoOne.value);
System.out.println(pojoTwo.value);
pojoTwo = pojoOne;
// You now have two variables holding a reference to
// a single instance of MyPojo. Changes made through
// either affect the same object. The object you
// originally instantiated and assigned to pojoTwo
// is no longer referenced by anything and will be
// garbage collected.
pojoOne.value = 3;
System.out.println(pojoTwo.value);
}
}
If in your code you're trying to copy the contents of the array referenced by cells to the array referenced by cellsX you would need to do so.
Since this is a multi-dimensional array you need to do a deep-copy; What you really have is an array of array references (since, again, arrays are objects in Java). This StackOverflow question covers that.
How can I clear a 6x6 "table", so that anything in it is cleared?
(I made the clearbutton already with ActionListener...etc)
//other code above that creates window, below is the code that creates the table I need to clear
square = new JTextField[s][s];
for (int r=0; r!=s; r++) {
symbols[r] = new JTextField();
symbols[r].setBounds(35+r*35, 40, 30, 25);
win.add(symbols[r], 0);
for (int c=0; c!=s; c++) {
square[r][c] = new JTextField();
square[r][c].setBounds(15+c*35, 110+r*30, 30, 25);
win.add(square[r][c], 0);
}
}
win.repaint();
}
Loop over the array and and set each element to null. You can use the java.utils.Arrays utility class to make things cleaner/neater.
for( int i = 0; i < square.length; i++ )
Arrays.fill( square[i], null );
Here is one line solution:
Arrays.stream(square).forEach(x -> Arrays.fill(x, null));
Something like...
for (int index = 0; index < square.length; index++) {
square[index] = null;
}
square = null;
Will do more then the trick (in fact the last line would normally be enough)...
If you're really paranoid...
for (int index = 0; index < square.length; index++) {
for (int inner = 0; inner < square[index].length; inner++) {
square[index][inner] = null;
}
square[index] = null;
}
square = null;