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。
爲什麼在'paintComponent'中調用'repaint'? –
「image」,「graphics2D」和「imageSize」在哪裏定義? –
你已經在clear和paintComponent方法中調用了repaint(),這是錯誤的。由於重繪本身會調用paintComponent – Blip