Question

I want to do efficient 2D drawing in Java. I would like to have some kind of surface which I may draw freely without having to let the view hierarchy traverse and update, which may cause stutter.

I have used a JPanel at first and called repaint() but I find it not to be optimal (and it is the reason I ask). The closest thing I have worked with is the Android's SurfaceView and it gives me a dedicated drawing surface.

To achieve this dedicated drawing surface, do I need to use OpenGL or is there any equivalent SurfaceView?

Was it helpful?

Solution

If you don't need Accelerated Graphics, you can draw onto a BufferedImage with Graphics2D. Once you have your data in the BufferedImage, you can simply paint the BufferedImage onto the component. This will avoid any sort of flickering you are talking about.

Creating the BufferedImage is easy:

int w = 800;
int h = 600;
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);

Then you can draw objects onto it with a graphics context (Possibly in your own render function):

Graphics2D g = bi.createGraphics();
g.drawImage(img, 0, 0, null);
//img could be your sprites, or whatever you'd like
g.dipose();//Courtesy of MadProgrammer
//You own this graphics context, therefore you should dispose of it.

Then when you repaint your component, you draw the BufferedImage onto it as one piece:

public void paintComponent(Graphics g){
    super.paintComponent(g);
    g.drawImage(bi, 0, 0, null);
}

Its sort of like using BufferedImage as a back buffer, and then once you are done drawing to it, you repaint it onto the component.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top