Graphics2D返回" NULL"总是

时间:2016-04-28 06:39:21

标签: java swing graphics paintcomponent

graphics2D正在返回" NULL"总是在下面的代码。由于没有调用putPixel()方法。我从表单设计中调用PictureBox。

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();
}

}

从main调用putPixel方法,其中我有(x,y)坐标存储在Point2D数组中。

1 个答案:

答案 0 :(得分:3)

由于您已从课程外部调用putPixel,并且尚未在构造函数中初始化graphics2Dimage,因此当您调用putPixel方法时可能该课程可能尚未显示。因此,只有在调用paintComponent时才会使graphics2D成为null,因为它会在显示此类时被调用。

解决方案可能是您将imagegraphics2D的初始化代码转移到构造函数,以便在调用null时不会遇到putPixel

注意

您不加区分地调用方法repaint()。您应该记住repaint()调用paint()方法,后者又调用paintComponent()方法。因此,如果您在repaint()方法中调用paintComponent(),则可能会遇到创建无限循环的风险。在这里,您在paintComponent中调用了两次,在clear方法中调用了paintComponent