Reputation: 61
I am creating a snake game and I am in need of using a JLayeredPane which will hold 2 Jpanels, this JLayeredPane will then be inserted into a JFrame. The reason I am doing this is because I need to have the base layer -- the game, and on top a layer which will spawn fruit onto the board. The reason I am not doing this directly onto the board is because the board is constantly being repainted, I need a method to randomly change the colour of the fruit for every time the player collects the fruit. The fruit however, will continuously change colour as the board is being repainted and a new random colour is generated based upon an array.
The problem with simply using a JLayeredPane is that I need the frame to fit perfectly with the components inside of it, setPreferredSize does not seem to do this as it does not take insets into account. When setResize(false), the insets do not match with the actual inset values, so I cannot simply add the insets.
So my question, how do I get the JLayeredPane to fit the JPanel's where the components within these JPanels have dimensions and then put this JLayeredPane into the JFrame.
Upvotes: 1
Views: 218
Reputation: 205865
As shown in How to Use Layered Panes: Setting a Component's Position Within Its Depth, use setBounds()
to position components within a JLayeredPane
.
Alternatively, override paintComponent()
in a JCOmponent
or JPanel
and render the fruit layer beneath the snake layer. If no resampling is required, drawImage()
is quite fast in this context.
Upvotes: 1