Java Graphics2D正在返回“;空";总是
graphics2D总是在下面的代码中返回“NULL”。由于此原因,未调用putPixel()方法。我从form design打电话给PictureBoxJava Graphics2D正在返回“;空";总是,java,swing,graphics,paintcomponent,Java,Swing,Graphics,Paintcomponent,graphics2D总是在下面的代码中返回“NULL”。由于此原因,未调用putPixel()方法。我从form design打电话给PictureBox public class PictureBox extends JPanel { Graphics2D graphics2D; static BufferedImage image; int imageSize = 300; public PictureBox(){ setDoubleBuffered(false); th
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方法正在从我有(x,y)的main调用坐标存储在Point2D数组中。由于您从类外调用了
putPixel
,并且没有在构造函数中初始化图形2D
和图像
,可能是当您都调用putPixel
方法时,类可能没有显示出来。因此,您将graphics2D
设置为null
,因为它仅在调用paintComponent时初始化,并且在显示此类时调用
解决方案可能是将图像
和图形2d
的初始化代码移到构造函数中,以便在调用putPixel
时不会遇到null
注意
您不分青红皂白地调用了方法
repaint()
。您应该记住,repaint()
调用paint()
方法,该方法反过来调用paintComponent()
方法。因此,如果在paintComponent()
方法中调用repaint()
,您将面临创建无限循环的风险。在这里,您在paintComponent
中调用了它两次,在clear
方法中调用了一次,该方法由paintComponent
调用 为什么在paintComponent
中调用repaint
?定义的image
、graphics2D
和imageSize
在哪里?在clear和paintComponent方法中调用了repaint(),这是错误的。正如重新绘制本身将调用paintComponent@JonnyHenly我只在PictureBox类中初始化了image、graphics2D和imageSize。在我的代码中没有显示这一点。1)请查看我不再费心修复的问题。2) 为了更快地获得更好的帮助,请发布一个or。3) 始终复制/粘贴错误和异常输出!4) 看&