NullPointerException für Java-Grafiken
Ich versuche, eine Methode zum Zeichnen eines bestimmten Teils eines Rasters zu implementieren. Dazu habe ich die paintComponent-Methode überschrieben:
public class Frame extends JPanel {
...
@Override
public void paintComponent( Graphics g ) {
super.paintComponent( g );
g.clearRect(0, 0, getWidth(), getHeight());
this.rectWidth = getWidth() / this.NUM_COLUMNS;
this.rectHeight = getHeight() / this.NUM_ROWS;
for (int i = 0; i < NUM_ROWS; i++) {
for (int j = 0; j < NUM_COLUMNS; j++) {
int x = i * this.rectWidth;
int y = j * this.rectHeight;
g.setColor( Color.WHITE );
g.fillRect( x, y, this.rectWidth, this.rectHeight );
}
}
}
}
Welche ist in Ordnung, aber dann möchte ich bestimmte Teile auf einen Funktionsaufruf wie folgt malen:
public void specificPaint( int coordinateX, int coordinateY, Color color ){
Graphics g = this.getGraphics();
int x = coordinateX * this.rectWidth;
int y = coordinateY * this.rectHeight;
g.setColor( color );
g.fillRect( x, y, this.rectWidth, this.rectWidth);
}
Der Anruf sollte wie @ se
// TESTING
this.modelMap.specificPaint( 40,40,Color.RED );
this.modelMap.specificPaint( 10,10,Color.RED );
this.modelMap.specificPaint( 20,25,Color.BLUE );
Ich erhalte einen Nullzeigerfehler mit dem Graphics-Objekt. Warum kann ich ihn nicht wiederherstellen und verwenden?
Gibt es einen besseren Ansatz?