2016-04-28 7 views
-1

graphics2Dは常に下のコードで「NULL」を返しています。そのため、putPixel()メソッドは呼び出されていません。私はフォームデザインからPictureBoxに電話しています。Graphics2Dが常に「NULL」を返しています

public class PictureBox extends JPanel { 

Graphics2D graphics2D; 
static BufferedImage image; 
int imageSize = 300; 

public PictureBox(){ 
    setDoubleBuffered(false); 
    this.setBorder(UIManager.getBorder("ComboBox.border")); 
    this.repaint();  
} 

public void paintComponent(Graphics g){ 

    super.paintComponent(g); 
     if(image == null){ 
      image = new BufferedImage(imageSize, imageSize, BufferedImage.TYPE_INT_RGB); 
      graphics2D = (Graphics2D)image.createGraphics(); 
      graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
      clear(); 
     } 
      Graphics2D g2D = (Graphics2D) g; 
      g2D.drawImage(image, 0, 0, this); 
    repaint(); 
} 

public final void putPixel(int x, int y, Color color) { 
    if(graphics2D != null){ 
    graphics2D.setColor(color); 
    graphics2D.drawLine(x, y, x, y); 
    repaint(); 
    } 
} 
public void clear() { 
    graphics2D.setPaint(Color.WHITE); 
    graphics2D.fillRect(0, 0, imageSize,imageSize); 
    repaint(); 
} 

}

putPixel方法は、iが(x、y)はPoint2Dのアレイに記憶された座標を有する場合、主から呼び出されています。あなたはクラスの外からputPixelと呼ばれている、あなたはそれはあなたがすべてのputPixelメソッドを呼び出すときにクラスが表示されていない可能性があることかもしれコンストラクタでgraphics2Dimageを初期化していないので

+2

なぜあなたは 'paintComponent'で' repaint'を呼び出しますか? –

+1

'image'、' graphics2D'と 'imageSize'はどこに定義されていますか? –

+1

あなたはclearとpaintComponentメソッドでrepaint()を呼び出しましたが、これは間違っています。再描画自体はpaintComponentを呼び出すでしょう。 – Blip

答えて

3

。したがって、graphics2Dnullになります。paintComponentが呼び出されたときにのみ初期化され、このクラスが表示されたときに呼び出されます。

ソリューションはputPixelを呼び出している間、あなたがnullが発生しないように、コンストラクタにimagegraphics2Dのための初期化コードをシフトすることが考えられます。あなたが方法repaint()を無差別に呼ばれている

NOTE

repaint()paint()メソッドを呼び出し、paintComponent()メソッドを呼び出すことに注意してください。したがってrepaint()メソッドをpaintComponent()メソッドの中に呼び出すと、無限ループが発生する危険性があります。ここでは、paintComponentで1回、paintComponentで呼び出されるclearの方法で2回呼びました。

+0

と呼ばれるときにのみ初期化されるので、graphics2Dがnullになるようにしています。 –

関連する問題