I am creating a volatile image in the following class, but hitting a NullPointerException every time. The reason why createVolatileImage() is returning null (from its JavaDoc) is that GraphicsEnvironment.isHeadless() is true.
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.VolatileImage;
import javax.swing.JPanel;
public class Tube extends JPanel {
private VolatileImage image;
private int width, height;
public Tube() {
super(true);
}
public Tube(int width, int height) {
this.width = width;
this.height = height;
createImage();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
开发者_Go百科if(image == null)
createImage();
if(image.validate(getGraphicsConfiguration()) == VolatileImage.IMAGE_INCOMPATIBLE)
createImage();
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
g2.drawImage(image, 0, 0, this);
}
public VolatileImage getBufferedImage() {
return this.image;
}
private void createImage(){
if(image != null){
image.flush();
image = null;
}
image = createVolatileImage(width, height);
image.setAccelerationPriority(1.0f);
}
}
How can I return a non-null VolatileImage ??
This would change the headless mode:
System.setProperty("java.awt.headless", "false");
You are calling the same method createImage() in three different pre-conditions.
1) When the constructor is called
2) When the image field is null
3) When the image field is not null
Your problem might lie in the implementation of the createImage() method.
You didn't include a stacktrace, but is the exception thrown from the constructor? If so, this is probably happening because the component is not displayable yet, so createVolatileImage
may return null
. Try removing the createImage
call from the constructor.
精彩评论