Hey, guys. Having a really hairy quandary here that perhaps you could help me with.
I’m working on a 2D adventure game engine, and doing the following:
- Rendering to an offscreen image, then getting the Graphics2D of a JPanel inside of / same size as my JFrame, rendering the image to the panel.
- That render performs a scale operation as well, so that my entire scene fits in the window regardless of the window size.
- Trying to render a Swing component or two over top of this panel. They should stay in the same position onscreen, even when the underlying panel scrolls to reveal more of the game scene.
- Manually repainting the object using a timer.
Here’s the issues I have:
-
Rendering Swing over the JPanel causes the Swing to flicker badly.
I tried using a JLayeredPane to help, it didn’t. -Dsun.java2d.noddraw and the other posted tweaks didn’t help either. The only solution I was able to find is to render the swing into the same graphics as my game objects (thus, onto the backbuffer) and then drawing it all at once. Now it doesn’t flicker as much, but the Swing rendering doesn’t look quite right and the game doesn’t acknowledge that I’ve clicked on the Swing object. -
Rendering performance is awful and seems to be fill-bound, as it gets significantly worse as the window gets bigger.
I recently tried switching the solution to a BufferedStrategy. I gained a ton of framerate by so doing, but the Swing was still an issue. Additionally, if I render to the JFrame’s Graphics2D object, in windowed (decorated) mode, the game seems to count the titlebar as part of the window and cost me 30 px of my scene’s image. Finally, without an Image object in hand, I can’t use the drawImage function that permits me to scale a rectangle of an image into another rectangle, which I have been using to get the window the appropriate size.
I also looked at using a RepaintManager but didn’t see much luck there either.
Here’s the solution I need; maybe one of you can point me in the right direction.
-
My scene is often bigger than the window, so I need to be able to scroll. Right now I am using a Rectangle as a “viewport”, copying out of the back buffer image (which is the size of the entire screen) only what is needed.
-
I need to be able to render Swing components on top of the still-refreshing Graphics2D work, either on a JPanel or in the JFrame itself without losing the pixels on the top of the window to the titlebar.
-
I need to be able to scale the final render so that it fits in the window regardless of the window’s size (or full screen). Optimally, the Swing components would scale also, but this is not crucial. They do, however, need to stay in place while the background (the game’s graphics) scroll.
-
I need rendering performance to not totally suck.
Can anyone help me with this conundrum?