Me gustaría comenzar diciendo que esto es una tarea. No quiero que me suministren la cuchara de respuesta, pero me gustaría saber qué está causando mis problemas.Java: rellenar un rectángulo en una cuadrícula
Actualmente estoy implementando Conway's Game of Life. Hacer clic en la celda debería cambiar el color, para representar que la celda se cambia a un estado activo. si vuelve a hacer clic, debería volver al color predeterminado.
Cuando hago clic en cualquier parte de la ventana, el programa arroja una Excepción del puntero nulo en la línea 56. Se han quedado atascados en esto durante el último día, por lo que se agradece cualquier ayuda. ¡Gracias!
Aquí está el código:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class VisibleGrid extends JPanel implements MouseListener, KeyListener{
CellGrid cellGrid;
Graphics rect;
public VisibleGrid(){
addMouseListener(this);
cellGrid = new CellGrid();
}
//Draw the grid of cells, 7px wide, 75 times to create 75x75 grid
public void paint(Graphics g){
for(int i=0; i<525;i=i+7){
for(int j = 0; j<525; j=j+7){
g.drawRect(i ,j,7,7);
}
}
}
//auxillary method called to fill in rectangles
public void paint(Graphics g, int x, int y){
g.fillRect(x, y, 7, 7);
repaint();
}
//main method, adds this JPanel to a JFrame and sets up the GUI
public static void main(String[] args){
JFrame j = new JFrame("Conway's Game of Life");
j.setLayout(new BorderLayout());
j.add(new VisibleGrid(), BorderLayout.CENTER);
JTextArea info = new JTextArea("Press S to Start, E to End");
info.setEditable(false);
j.add(info, BorderLayout.SOUTH);
j.setSize(530,565);
j.setVisible(true);
}
//these methods are to satisfy the compiler/interface
//Begin Mouse Events
public void mouseExited(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void mouseClicked(MouseEvent e){
//fill the selected rectangle
rect.fillRect(e.getX(), e.getY(), 7,7);
repaint();
//set the corresponding cell in the grid to alive
int row = e.getY() /7;
int column = e.getX() /7;
cellGrid.getCell(row, column).setAlive(true);
}
//End Mouse Events
//These methods are to satisfy the compiler/interface
//Begin KeyEvents
public void keyReleased(KeyEvent e){}
public void keyPressed(KeyEvent e){}
public void keyTyped(KeyEvent e){}
}
¿Qué línea es la línea 56? Cuando copié/pegué el código, fue int column = e.getX()/7; que no se ve bien –
apuesto a que la línea 56 es _rect.fillRect (e.getX(), e.getY(), 7,7); _ –
Como dice @guido, asegúrese de que el objeto gráfico, 'rect' se inicializa o tiene una referencia válida, antes de acceder a ella. – Rupak