Reputation:
I´ve got a two dimensional Array (Matrix) with the Dimension 50x50. In these Matrix every position has the value 0 or 1. This Matrix is presented by a Grid Layout with 50x50 Buttons, which are white oder black, if the value is 0 or 1. If I press a Button the related position in the Matrix should change the value to 1. To implement this I create the Grid with one Button for each matrixposition, performed by a for-loop. I also implementet a ActionListener for each Button in this for-loop. I tried to change the value of the position using the ActionListeners, by giving the function creating the button and the ActionListener for each position two parameters for row and column of the position in the matrix. But theres a mistake, so I always get a NullPointerException, if I press a Button.
import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Bild extends JFrame {
public Matrix matrix;
public JButton createButton(int a, int x, int y) {
JButton b = new JButton();
if(a==1){
b.setBackground(Color.WHITE);
}else{
b.setBackground(Color.BLACK);
}
b.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent arg0 ) {
matrix.matrix[x][y]=1;
}
});
this.add(b);
return b;
}
public Bild(Matrix matrix) {
matrix = matrix;
GridLayout layout = new GridLayout(50,50,0,0);
this.setLayout(layout);
for (int i = 0; i<50; i++) {
for(int j=0; j<50; j++){
if (matrix.matrix[i][j]==0){
this.add(createButton(1,i,j));
}else{
this.add(createButton(2,i,j));
}
}
}
}
}
public class Matrix{
int[][] matrix;
public Matrix(){
matrix = new int[50][50];
for(int i=0; i<50; i++){
for(int j=0; j<50; j++){
matrix[i][j]=0;
}
}
}
}
import javax.swing.*; // JFrame, JPanel, ...
import java.awt.*; // GridLayout
public class Main{
public static void main (String[] args) {
Matrix matrix = new Matrix();
JFrame frame = new Bild(matrix);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
}
}
Upvotes: 0
Views: 71
Reputation: 2841
public Bild(Matrix matrix) {
matrix = matrix;
}
matrix hides your class variable, so you must reffer to it this.matrix when you reffer to class one ,
shoud be this.matrix=matrix
Thats why you get NPE.
For more information https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
Upvotes: 1