Search code examples
javaimageswingjava-2d

Create VolatileImage always return null


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);
        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 ??


Solution

  • This would change the headless mode:

    System.setProperty("java.awt.headless", "false");