Ich möchte damit beginnen zu sagen, dass dies eine Aufgabe ist. Ich möchte nicht, dass mir der Löffel der Antwort gefüttert wird, aber ich würde gerne wissen, was meine Probleme verursacht.Java: Füllen eines Rechtecks in einem Raster
Ich implementiere gerade Conways Game of Life. Durch Klicken auf die Zelle sollte die Farbe geändert werden, um anzuzeigen, dass die Zelle in einen aktiven Zustand versetzt wurde. Wenn Sie erneut darauf klicken, sollte es zur Standardfarbe zurückkehren.
Wenn ich irgendwo in das Fenster klicke, löst das Programm eine Null-Zeiger-Ausnahme in Zeile 56 aus. Seit dem letzten Tag sind sie hier festgefahren, so dass jede Hilfe geschätzt wird. Vielen Dank!
Heres der Code:
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){}
}
Welche Linie ist Linie 56? Wenn ich den Code kopiere/eingefügt habe, war es int column = e.getX()/7; was nicht richtig aussieht –
ich Wette Zeile 56 ist _rect.fillRect (e.getX(), e.getY(), 7,7); _ –
Wie @guido sagt, stellen Sie sicher, dass das Grafikobjekt, 'rect' wird vor dem Zugriff initialisiert oder hat eine gültige Referenz. – Rupak