これは割り当てであると言うことから始めたいと思います。私は答えのスプーンが私に与えられるのを望んでいないが、何が私の問題を引き起こしているのか知りたい。Java:グリッド上の長方形で塗りつぶす
私は現在ConwayのGame of Lifeを実装しています。セルをクリックすると、そのセルがアライブ状態に切り替わることを表す色が変更されます。再度クリックすると、デフォルトの色に戻ります。
私がウィンドウのどこかをクリックすると、プログラムは56行目にNull Pointer Exceptionをスローします。最後の1日ほどでこれに固執しています。ありがとう!
相続コード:
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){}
}
どの行が56行目ですか?コードをコピー/ペーストすると、int column = e.getX()/ 7;それは正しく表示されません –
私はベットライン56が_rect.fillRect(e.getX()、e.getY()、7,7); _ –
です。@guidoによれば、グラフィックスオブジェクトである 'rect'それにアクセスする前に、初期化されているか、または有効な参照があります。 – Rupak