Skip to content
Advertisement

How to do image rendering using bufferedimage in a jframe?

I am trying to render a complicated set of objects, and instead of trying to render each object individually, I thought it would be faster to render them as a BufferedImage. The only way I could figure out how to do that was to turn the BufferedImage into an ImageIcon, and set that to a JLabel, and add the JLabel to the JFrame. To update the image, I remove the JLabel, set it with the new BufferedImage, and re-add it to the JFrame. This makes the screen flash rapidly as you can see an empty frame in between each rendering. If I don’t remove the label, the program runs extremely slowly. How do I fix this? Should I even be using JLabels or is there a better way?

JavaScript

I doubt the problem has to do with the loop itself, but I’m including it anyway just in case.

JavaScript

Advertisement

Answer

JavaScript

I would suggest there is no need to remove/add the label or pack the frame since I would assume the Icon will be the same size every time.

All you need to do is replace the Icon of the label.

JavaScript

I am trying to render a complicated set of objects, and instead of trying to render each object individually, I thought it would be faster to render them as a BufferedImage

Otherwise just do the rendering in your paintComponent() method. Swing is double buffered by default so it essentially removes the need to create the BufferedImage.

See: get width and height of JPanel outside of the class for an example of custom painting. Just update the ball count from 5 to 100 to make it more complex.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement