Null Pointer Exception on a 2D array (Java) - java

I have a class, "Tetris", in which one of the instance variables is "board". "board" is 2D array of Color objects. Upon the creation of a tetris object I call a method that sets the dimensions of board and then sets all of the Color objects to be the Default value, that is to say, Color.blue.
public Tetris(int rows, int cols) {
this.rows = rows;
this.cols = cols;
reset(rows, cols);
}
public void reset(int rows, int cols) {
Color[][] board = new Color[rows][cols];
for(int i = 0; i<this.rows; i++) {
for(int j = 0; j<this.cols; j++) {
board[i][j] = DEFAULT_COLOR; // Color.blue; //DEFAULT-COLOR
}
}
}
Unfortunately, when I run the code (which obviously has not been posted in its entirety) I get a null pointer exception on the line:
board[i][j] = DEFAULT_COLOR; // Color.blue; //DEFAULT-COLOR.
Is there anything obviously wrong with what I am doing?

It would help if you would post a short but complete program which demonstrated the problem. The code you've posted isn't enough to throw an exception, but I can see how with a few changes it might.
In particular, it seems odd to me that you're declaring a new local variable within your reset method... and you also have an instance variable called board? I suspect the solution may be as simple as changing the start of reset to:
board = new Color[rows][cols];
If your real code uses the local variable to create the array, but then tries to assign values via the instance variable, that could very well be the cause of the problem.
It also seems wrong that you're passing rows and cols into the method, and using those parameters in one place but the instance variables this.rows and this.cols in the loop. Why bother passing them at all?

I think you must allocate every one of those colors like this:
board[i][j] = new Color(...

Related

Final variable being changed without any = statements

I'm making an autoclicking project in java for personal use, and using the following method to get coordinates of a click from a class that extends MouseAdapter. The click is being done on a JFrame.
int[] mouseCoordinates = new int[2]; //The coordinates of the click
mouseCoordinates = mouseListenerExample.getCoordinates();
final int[] baseCoordinates = mouseCoordinates; //The base coordinates (no click) which is this problem//
int[][] totalCoordinates = new int[4][2]; //An array that collects all coordinates of 4 mouse clicks
for (int i = 0; i < 4; i++){ //the goal is to get the coordinates of 4 clicks
while (mouseCoordinates[0] == baseCoordinates[0]){
mouseCoordinates = mouseListenerExample.getCoordinates(); //The problem occurs here: when mouseListenerExample.getCoordinates() changes, mouseCoordinates is changed, baseCoordinates is also changing, which it shouldnt, since there are no statements that say so.
if (mouseCoordinates[0] != baseCoordinates[0]) {
break;
}
}
totalCoordinates[i] = mouseListenerExample.getCoordinates();
mouseListenerExample.setCoordinates(baseCoordinates);
mouseCoordinates = baseCoordinates;
}
Is there some statement that is changing baseCoordinates that I am missing?
Your baseCoordinates variable has been declared final, and so it cannot change, but since it is an int[] or int-array, it is a reference variable, and so what cannot change is the reference itself, not the state of the reference, and so the ints held within the array can (and in your case -- do) change.
You're changing the values held by mouseCoordinates. Since the baseCoordinates refers to the exact same int[] object, then this will likewise change the values for baseCoordinates. Best to create a completely new int object for the final variable if you don't want it changed.
Do something like:
final int[] baseCoordinates = new int[mouseCoordinates.length];
System.arraycopy( mouseCoordinates, 0, baseCoordinates , 0, mouseCoordinates.length );
So after some looking around, i just replaced the arrays with individual ints, and added a print statement right before the break, and it made it work.

How to create 2d arrayobject for a custom class

I have custom class called ButtonList, like a list of buttons, i am adding all the buttons that are going into the window to that 2d array object of button list.
ButtonList[][] buttonList;
buttonList = new ButtonList[5][3];
and I'm constantly getting Null pointer error when im am trying to add the
JButtons to the buttonList.
this.buttonList[column][row].addButton(buttonImage);
ButtonList and addButton method looks like so:
static class ButtonList{
int column = 0;
int row = 0;
JButton[][] arrayButton = new JButton[this.column][this.row];
void addButton(JButton BUTTON){
arrayButton[this.column][this.row] = BUTTON;
System.out.println("Row: " + this.row + " Column: " + this.column);
this.column += 1;
this.row += 1;
System.out.println("button inserted at " + this.row);
}//end addButton
what is it that i am doin wrong?
thanks
int column = 0;
int row = 0;
JButton[][] arrayButton = new JButton[this.column][this.row];
You initialize your array before your constructor get called. So at this point your column and row are still 0. You initialize then an array of [0][0]. This is why later on you get a null pointer exception even though you may have changed the values of row and column in your constructor or later on in any method. But at the time of the creation they were 0.
Moreover
arrayButton[this.column][this.row] = BUTTON;
This is quite probable to give you a out of bounds exception because arrays in java are 0 indexed so your valid range is from [0,column-1][0,row-1] so you may want to fix this as well.
JButton[][] arrayButton = new JButton[this.column][this.row];
this line create an 2d array (without initialization), and infact is equivalent to this:
JButton[][] arrayButton = new JButton[0][0];
0 happens to be the value of the column and row at that time. Changing the value of these two variables does not take any effect on the array it self.
Solution:
If you know in advance the max value of column and row, use that value for array creation. If not, use ArrayList, you will be able to change your size later.

Deep copies of 2d object array

how can I make on a button press a new deep copy of a 2 dimensional array?
Basically I created a game field with buttons. The game is called sokoban and it's a puzzle. The player is moving from one button to the other with arrow keys on a fixed map (8x8 buttons).
I want to implement an undo function. So I thought that I just create a deep copy of the JButton array before each move and save it into a stack. So when I press the undo button it calls the pop function of my stack. The problem is that I need to declare and initialize another JButton[][] where I can save the game field to before each move. Since I want infinite possible moves and also undos it seems impossible to me. I can't declare and initalize infite diffrent JButton[][] arrays. Any idea on how I can solve that?
That's how I copy a 2d object array:
JButton[][] tempArray = new JButton[jbArray.length][jbArray[0].length];
for (int i = 0; i < getJbArray().length; i++) {
for (int j=0;j<getJbArray()[0].length;j++) {
tempArray[i][j]=jbArray[i][j];
}
}
movesStack.push(tempArray);
Unfortunately you can't clone swing components in general, as they do not implement the Cloneable interface. As I see it you have two options:
Create a new JButton inside your double loop and copy whatever properties (like alignment, color etc.) you have set to the new JButton
Write your own class that extends JButton and implement the Cloneable interface
The first way is somewhat of a hack and not very robust or reusable. The second way is much better practice. In this case you'll have to define how the deep copy is supposed to happen, and ensure that all relevant properties are copied over.
You've got the right idea. You're not quite going deep enough.
public JButton[][] copy(JButton[][] jbArray) {
JButton[][] tempArray = new JButton[jbArray.length][jbArray[0].length];
for (int i = 0; i < jbArray.length; i++) {
for (int j = 0; j < jbArray[0].length; j++) {
tempArray[i][j] = new JButton(jbArray[i][j].getText());
}
}
return tempArray;
}
Rather than copying JButtons, you should have a model that you use to set the JButtons. Maybe a ModelClass[][] array?

Is it possible to make an Array of Rectangles in Java

I am trying to make a very simple grid in which a user can move through. Through my research i have concluded that the best way to achieve this would be using a two-dimensional array to represent the grid. However i am unsure of how to draw this array to a Jframe or Jpanel if i were to make an array of rectangles.
Many Stackoverflow questions seem to ask simmilar queries but unforunately i have found non that entirely explains how to draw a simple grid of rectangles.
You can make arrays out of everything. Notice how the way to implement an array is
*datatype* [] *arrayname* = new *datatype* [*lengthOfArray*];
Lets say the name of the class that contains the rectangles is RECTANGLE. So if you want an Array, that contains, lets say, 5 rectangles, it would look somewhat like that:
RECTANGLE [] rectangelArray = new RECTANGLE [5];
If you want to take that to a 2 dimensional Level, just add another bracket:
RECTANGLE [][] rectangelMatrix = new RECTANGLE [4][5];
Assuming that by "drawing to the JPanel" you mean that you want to put the rectangles onto the screen, you would then have a for-loop in a for-loop, that would for example call each rectangle to draw itself:
for(int i = 0; i<rectangleMatrix.length; i++){
for(int j = 0; j<rectangleMatrix[i].length; j++){
rectangleMatrix[i][j].draw();
}
}
rectangleMatrix.draw() calls a method that will draw the rectangle based on its coordinates and size. you could also in a similar fashion call a method that will read the information of each rectangle and then draw it based on that information. This will help you seperate between information and drawing purposes in your classes, which is always a good thing to do:
for(int i = 0; i<rectangleMatrix.length; i++){
for(int j = 0; j<rectangleMatrix[i].length; j++){
drawRectangle(rectangleMatrix[i][j]);
}
}
drawRectangle(RECTANGLE toDraw) is in the same class that you have the method with the for-loop in.
In your parent component of grid set layout like
gamePanel.setLayout(new GridLayout(ix, iy));
where ix and iy is dimension size
you also need array of cells private Cell[][] cells; in this case cell is simply
public class Cell extends JPanel{
//some game specific code, fields, constructors
}
now use it
for (int i = 0; i < ix; i++) {
for (int j = 0; j < iy; j++) {
progres.setValue(progres.getValue() + 1);
cells[i][j] = new Cell(i, j, passer);
gamePanel.add(cells[i][j]);
}
}
now if in constructor of cell you will set a border this.setBorder(new LineBorder(Color.GRAY)); grid will appear. in cell constructor or setter method you can also pass whole cells so each cell will be aware of another, and be able to interact with them. but be aware- if you pass it in loop that also create cells, you might encounter a null values.
this way you can use swing components so each cell can be clickable etc.
You can extend a JComponent and overriding its paint(Graphics) method to draw the grid using Graphics.drawLine.
If you need the grid cells to be interactive in some way, then you should probably just create components with rectangular borders and position them using a grid layout.

"Metaaccess" of Objects in Java With Variables in the Identifiers

I want to access to a certain number of objects in Java without write a lot of code, for example:
int X;
for(X=0;X<5;X++){
jLabelX = /*do something*/
}
Would be something like this:
When X=0 then jLabel0 is access, X=1 then jLabel1 and so on...
Is there any way of doing this? or i need to specify all the cases
The best way of doing this is to not have variables called jLabel0, jLabel1 etc in the first place. Instead, have an array variable (or some other collection):
JLabel[] labels = new JLabel[5];
for (int i = 0; i < labels.length; i++) {
labels[i] = new JLabel();
// Whatever
You can get at fields with reflection, but any time I see variables x0, x1, x2 etc I shudder - it's a clear indication that a collection of some kind is a better fit.

Categories

Resources